Question

Is there a clean way to conditionally pass as a block as an argument to another method in Ruby?

In my Rails app I'm defining some customized ActionMailer behavior with a wrapper and I want to elegantly handle implicit (no block given) and explicit (block given) view templates.

class Mailer < ::ActionMailer::Base
  # ...
  def signed_mail(opts = {}, &block)
    # ...
    mail mail_opts, &(block_given? ? block : nil)
  end
end

Is there a more idiomatic way to optionally pass the given block to mail? The ternary operator provides for DRYer code than using an if/else, but still looks awkward.

Was it helpful?

Solution

You don't have to do anything special for the case where no block was passed:

class Mailer < ::ActionMailer::Base
  # ...
  def signed_mail(opts = {}, &block)
    # ...
    mail mail_opts, &block
  end
end

If no block was given, block will already be nil, so this will faithfully pass along the lack of block.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top