2010-09-14 111 views
3

在我目前的Rails(Rails的2.3.5,红宝石1.8.7)的应用程序,如果我想能够定义像一个帮手:可选参数

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 

...和然后从一个视图,或者把它:

<%= product_image_tag(p) %> 

...或:

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

换句话说,我希望能有这样的helper方法接受一个可选大小参数。什么是最好的方式去做这件事?

回答

10

你在正确的轨道上。我这样做:

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 

说明:

最后一个参数设置为空哈希是一种常见的Ruby成语,因为你可以调用像product_image_tag(product, :a => '1', :b => '2', :c => '3', ...)的方法而不{}明确使得剩余的参数哈希。

options[:size] ||= "200x200"将:size参数设置为200x200,如果没有传递给方法。

if img = product.product_images.first - Ruby可以让你在一个条件内进行赋值,这非常棒。在这种情况下,如果product.product_images.first返回零(无图像),则返回到placehold.it链接,否则显示第一个图像。

+0

完美!非常感谢。 – yalestar 2010-09-14 20:51:57