简体   繁体   中英

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

I have a helper that creates mailer template rows (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'. Is this possible in 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 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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