Rails Image Helper 的可选参数
在我当前的 Rails(Rails 2.3.5、Ruby 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) %>
在其他中换句话说,我希望能够让这个辅助方法采用可选的大小参数。解决这个问题的最佳方法是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你走在正确的轨道上。我会这样做:
解释:
将最终参数设置为空散列是常见的 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
返回 nil(无图像),您将退回到 placehold.it 链接,否则显示第一张图像。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 200x200 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.first
returns nil (no image), you fall back to your placehold.it link, otherwise display the first image.