In my current Rails (Rails 2.3.5, Ruby 1.8.7) app, if I would like to be able to define a helper like:
def product_image_tag(product, size=nil)
html = ''
pi = product.product_images.first.filename
pi = "products/#{pi}"
pa = product.product_images.first.alt_text
if pi.nil? || pi.empty?
html = image_tag("http://placehold.it/200x200", :size => "200x200")
else
html = image_tag(pi, size)
end
html
end
…and then call it from a view with either:
<%= product_image_tag(p) %>
…or:
<%= product_image_tag(p, :size => 20x20) %>
In other words, I’d like to be able to have this helper method take an optional size parameter. What would be the best way to go about this?
You’re on the right track. I would do this:
Explanations:
Setting the final parameter to an empty hash is a common Ruby idiom, since you can call a method like
product_image_tag(product, :a => '1', :b => '2', :c => '3', ...)without explicitly making the remaining arguments a hash with{}.options[:size] ||= "200x200"sets the :size parameter to 200×200 if one wasn’t passed to the method.if img = product.product_images.first– Ruby lets you do assignment inside a condition, which is awesome. In this case, ifproduct.product_images.firstreturns nil (no image), you fall back to your placehold.it link, otherwise display the first image.