2012-09-12 77 views
0

我從1.8.x的不知道升級的Ruby 1.9.3如果小馬寶玉在這個過程過於升級,但問題是,我使用此代碼來發送電子郵件的如何不通過參數如果是空的?

Pony.mail(
    :to => to, 
    :from => from, 
    :subject => subject, 
    :body => Nokogiri::HTML(body_with_footer).text, 
    :html_body => body_with_footer, #.gsub("\n","<BR>"), 
    :attachments => attachment_to_send, 
    :via => :smtp, 
    :via_options => { 
      :address  => $smtp, 
      :port  => $smtp_port, 
      :enable_starttls_auto => false 
    } 
) 

attachment_to_send應該是一個要附加的文件的哈希值。當散列爲空時,不發送附件。現在我得到一個小馬錯誤抱怨哈希是「」​​。

因此,我介紹瞭如果條件attachment_to_send==""所以我打電話給小馬有或沒有附件部分。

有什麼辦法可以管理嗎?所以我只有一個代碼,我叫小馬?

回答

1

與三元運算處理attachment_to_send.empty? ? nil : attachment_to_send

 details = { 
      :to => to, 
      :from => from, 
      :subject => subject, 
      :body => Nokogiri::HTML(body_with_footer).text, 
      :html_body => body_with_footer, #.gsub("\n","<BR>"), 
      :attachments => attachment_to_send.empty? ? nil : attachment_to_send , 
      :via => :smtp, 
      :via_options => { 
        :address  => $smtp, 
        :port  => $smtp_port, 
        :enable_starttls_auto => false 
      } 


Pony.mail(details) 
1

通過檢查以下方式空狀態準備附着陣列,

tmp_hash = {:to => to, 
      :from => from, 
      :subject => subject, 
      :body => Nokogiri::HTML(body_with_footer).text, 
      :html_body => body_with_footer, #.gsub("\n","<BR>"), 
      :via => :smtp, 
      :via_options => { 
          :address  => $smtp, 
          :port  => $smtp_port, 
          :enable_starttls_auto => false 
          } 
      } 

tmp_hash[:attachments] => attachment_to_send 
tmp_hash[:attachments] => nil if attachment_to_send.empty? 

或 直接,

tmp_hash[:attachments] => attachment_to_send if not attachment_to_send.empty? 

然後

Pony.mail(tmp_hash) 

應該工作