Advanced Options for the Rails Image Helper

In my current Rails (Rails 2.3.5, Ruby 1.8.7) application, if I would like to be able to define an assistant, for example:

  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 the view with:

<%= product_image_tag(p) %>

... or:

<%= product_image_tag(p, :size => 20x20) %>

In other words, I would like to be able to use this helper method with an optional size parameter. What would be the best way to do this?

+3
source share
1 answer

You are on the right track. I would do this:

def product_image_tag(product, options = {})
  options[:size] ||= "200x200"

  if img = product.product_images.first
    image_tag("products/#{img.filename}", :alt => img.alt_text, :size => options[:size])
  else
    image_tag("http://placehold.it/#{options[:size]}", :size => options[:size])
  end
end

Explanations:

Setting the final parameter to an empty hash is a common Ruby idiom, since you can call a type method product_image_tag(product, :a => '1', :b => '2', :c => '3', ...)without making extra arguments hash with {}.

options[:size] ||= "200x200" size: 200x200, .

if img = product.product_images.first - Ruby , . , product.product_images.first nil ( ), placehold.it, .

+10

Source: https://habr.com/ru/post/1764763/


All Articles