Radek
Radek

Reputation: 11121

How to not to pass argument if empty?

I upgraded ruby to 1.9.3 from 1.8.x Not sure if pony gem was upgraded during that process too but the point is that I was using this code to send out an emails

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 should be a hash of files to be attached. When the hash was empty no attachment was send. Now I got a pony error complaining about the hash being "".

So I introduced a if condition attachment_to_send=="" so I call pony with or without the attachment part.

Is there any way to manage that? So I have only one code where I call pony?

Upvotes: 0

Views: 99

Answers (2)

maximus ツ
maximus ツ

Reputation: 8065

prepare your attachment array by checking empty condition following way,

 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
                             }
             } 

and

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

or directly,

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

and then

Pony.mail( tmp_hash)

should work

Upvotes: 1

AnkitG
AnkitG

Reputation: 6568

handled with ternary operator 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)

Upvotes: 1

Related Questions