如果条件为真,如何添加到选项哈希?

时间:2014-01-08 12:30:20

标签: ruby-on-rails ruby

在我的Rails项目中,我有这个邮件程序类:

class ProjectMailer < ActionMailer::Base

  def send_project_link(delivery)
    @delivery = delivery
    mail(:from     => @delivery.sender_email, 
         :to       => @delivery.recipient_email, 
         :bcc      => [@delivery.sender_email],
         :subject  => @delivery.subject)
  end

end

在哈希中包含或不包含键/值对:bcc的最简洁方法是什么,具体取决于是true还是false

感谢您的帮助。

3 个答案:

答案 0 :(得分:3)

mail(
  {
    from:    @delivery.sender_email, 
    to:      @delivery.recipient_email, 
    subject: @delivery.subject,
  }
  .tap{|h| h[:bcc] = [@delivery.sender_email] if @delivery}
)

答案 1 :(得分:2)

要在选项中不包含:bcc键,您可以这样做:

class ProjectMailer < ActionMailer::Base
  def send_project_link(delivery, send_with_bcc=false)
    @delivery = delivery
    mail_options = {
      :from     => @delivery.sender_email, 
      :to       => @delivery.recipient_email, 
      :subject  => @delivery.subject
    }  
    mail_options[:bcc] = [@delivery.sender_email] if send_with_bcc
    mail(mail_options)
  end
end

答案 2 :(得分:1)

我可能会这样做......

def send_project_link(delivery. bcc? = false)
  @delivery = delivery
  mail_options = {:from     => @delivery.sender_email, 
                  :to       => @delivery.recipient_email, 
                  :subject  => @delivery.subject
                 }
  mail_options[:bcc] = [@delivery.sender_email] if bcc?
  mail mail_options
end