简体   繁体   English

Rails-将选项传递到接受块的辅助方法中?

[英]Rails - Pass options into a helper method that accepts a block?

I have a helper that creates mailer template rows (html). 我有一个创建邮件模板行(html)的助手。 I want to be able to pass in styles to the row (optionally), like a background color. 我希望能够将样式传递给行(可选),例如背景色。

module MailHelper
  def module_row(&block)
    h << "<table border='0' cellpadding='0' cellspacing='0' width='100%'>"
    # more table html here
    h << capture(&block)
    # more table html here
    h << "</table>"
    raw h
  end
end

I want to be able to optionally pass in a background color, but I can't seem to figure out how to do that while passing in the '&block'. 我希望能够有选择地传递背景色,但是在传递“&block”时似乎无法弄清楚该如何做。 Is this possible in Ruby? 在Ruby中有可能吗?

You sure can! 你当然可以!

module MailHelper
  def module_row(options={}, &block)
    ...
    if options[:foo]
      do_foo_stuff
    end
  end
end

<% module_row(foo: true) do |x| %>
  ...
<% end %>

Common practice is to define defaults like this: 常见的做法是定义默认值,如下所示:

def module_row(options={}, &block)
  opts = { 
    foo: true,
    background_color: 'black'
  }.merge!(options)

  if opts[:foo]
    do_foo_stuff
  end
end

You can pass options as a Hash well, like: 您可以将选项作为哈希很好地传递,例如:

module MailHelper
  def module_row(**opts, &block)
    bgcolor = opts[:bgcolor] || '#FFFFFF'
    ...
    h << "<table border='0' cellpadding='0' cellspacing='0' width='100%'>"
    # more table html here
    h << capture(&block)
    # more table html here
    h << "</table>"
    raw h
  end
end

Then you can call: 然后,您可以致电:

module_row(bgcolor: '#AAAAAA', &my_block)

or: 要么:

module_row(bgcolor: '#AAAAAA') { block content }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM