DRYing Up Our Testimonial Partial

So for those of you that ran through the and created your very own random testimonial helper, I’m going to create another help to and were are going to make a few updates to our partial. First we have to do a few things:

  1. Rename our _random_testimonial.rhtml partial to _testimonial.rhtml
  2. Open our partial and remove the random_ from lines 2 and 3 leaving testimonial.[object]
  3. Open our application_helper.rb and edit out random_ on the line rendering the partial.
  4. Give the code a test

Everything should be just fine. All we have done is removed the usage of “random_” when it comes to using our partial. All the other code is the same here. So why would we do such a thing? Well… what if we had a page that we wanted to show all of our testimonials on? We already have a perfectly good partial view – we might as well take advantage of it. So in my testimonials_helper.rb I make another helper as such:

def all_testimonials
  @testimonials = Testimonial.find(:all)
  render(:partial => 'shared/testimonial', :collection => @testimonials)
end

Notice how I’m using the same partial here. Now in my testimonials controller I’ll just create a blank index method. The in my view testimonials/index.rthml I’ll just call the <%= all_testimonials %> helper.

Now I can use the both helpers with the same partial depending on the output I’m trying to active.

Now granted, we could use a method supporting polymorphism to DRY this up a little more, but I’ll let you experiment more with that yourself, when it comes to displaying testimonials on a page I don’t think I’m going to take the code THAT far.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s