How to not to pass argument if empty? - ruby

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?

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)

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

Related

Mail sent twice or more instead of once using rails 3.2

I am working with rails 3.2 and ruby 2.1.2p95. Through my application, sending 1000+ of emails. I want to send few email from smtp and few emails from sendgrid. So I have configured like below in Notifier.rb file
after_filter :set_delivery_options, :except => [:method1]
def set_delivery_options
message.delivery_method.settings.merge!(
:address => "smtp.gmail.com",
:port => 587,
:domain => "xxxxxxxx",
:user_name => "xxxxxxxxxxxxx",
:password => "xxxxxxxxxxxxx",
:authentication => "plain",
:enable_starttls_auto => true
)
end
My method is like below:
def customer_mailing(customer)
mail(
:to => customer.user.email,
:subject => "Testing",
#:bcc => EMAIL_BCC,
:content_type => "text/html"
)
set_headers
end
Whenever I call the above method, the mail is sending twice or more in some times on production server.

Can't get value from nested pair in Omniauth hash.

I'll try to keep this simple, my previous wording was maybe a bit too verbose:
Here is the example Omniauth hash: https://github.com/mkdynamic/omniauth-facebook
I can access and save some values from this but not others. The field is writable, so I know its just my syntax (beginner, sorry!)
{
:provider => 'facebook',
:uid => '1234567',
:info => {
:nickname => 'jbloggs',
:email => 'joe#bloggs.com',
:name => 'Joe Bloggs',
:first_name => 'Joe',
:last_name => 'Bloggs',
:image => 'http://graph.facebook.com/1234567/picture?type=square',
:urls => { :Facebook => 'http://www.facebook.com/jbloggs' },
:location => 'Palo Alto, California',
:verified => true
},
:credentials => {
:token => 'ABCDEF...', # OAuth 2.0 access_token, which you may wish to store
:expires_at => 1321747205, # when the access token expires (it always will)
:expires => true # this will always be true
},
:extra => {
:raw_info => {
:id => '1234567',
:name => 'Joe Bloggs',
:first_name => 'Joe',
:last_name => 'Bloggs',
:link => 'http://www.facebook.com/jbloggs',
:username => 'jbloggs',
:location => { :id => '123456789', :name => 'Palo Alto, California' },
:gender => 'male',
:email => 'joe#bloggs.com',
:timezone => -8,
:locale => 'en_US',
:verified => true,
:updated_time => '2011-11-11T06:21:03+0000'
}
}
}
I can do this to get gender and save it.
location:auth.extra.raw_info["gender"]
Obviously though I dont want to save gender to location. I want to get "Palo Alto" and save it. But this doesn't work.
location.auth.extra.raw_info["location"]["name"]
What am I doing wrong? When I try it in console, I'm able to get the value.
try this
location.auth.extra.raw_info.location.name
or this
location.auth.extra.raw_info[:location][:name]
Yeah, what you suggested was what I was trying...and it turns out we were right but FB had changed how that hash was set up so it wasn't working. Lesson learned: subscribe FB's notifications next time :)

Using pony gem and ckeditor in my rails 3 application to send bulk mailing

I am using ckeditor im my application for bulk mailing using pony gem mail is getting sent but I have a couple of problems:
Some tags are also delivered in mail.
If I apply effects to text like bold, italic, underline etc are visible in mail
Image is not visible instead of that {"body"=>" is visible.
Following is the code...
My pony mail function...
params[:l].each do |single_email|
p single_email
Pony.mail(:to => single_email, :from => 'example#example.co.in', :subject => #bmail.subject,
:headers => { "Content-Type" => "text/html"}, :body => #bmail.body, :via => :smtp, :via_options => {
:address => "smtp.gmail.com",
:port => 587,
:domain => 'example.co.in',
:user_name => 'example#example.co.in',
:password => 'paswd',
:authentication => 'plain',
:enable_starttls_auto => true
}) end
Call to ckeditor
%br = cktext_area :body, :body, :ckeditor => {:uiColor => "#AADC6E", :toolbar => "mini"}
%br
Please help me to deliver perfect mail with image and stuffs, plz help me as soon as possible.
Thanz in advance.
try :html_body => #bmail.body
http://rubydoc.info/gems/pony/1.4.1/frames

2 forms on same page, Sending using Pony in Sinatra, same email address

i am using Pony.mail to send mail within Sinatra, what i have now is two forms, one that only sends an email address for subscription to newsletter and the second form is a contact form, both are going through the same action.
What I am trying to achieve is if the subscription field is completed then only send those params or if the contact form is completed and sent then send those params
Heres what i come up with so far, but getting undefined method nil
post '/' do
require 'pony'
Pony.mail(
:from => params[:name] || params[:subscribe],
:to => 'myemailaddress',
:subject => params[:name] + " has contacted you via the Website" || params[:subscribe] + " has subscribed to the newsletter",
:body => params[:email] + params[:comment],
:via => :smtp,
:via_options => {
:address => 'smtp.gmail.com',
:port => '587',
:enable_starttls_auto => true,
:user_name => 'myemailaddress',
:password => 'mypassword',
:authentication => :plain,
:domain => "localhost.localdomain"
})
redirect '/success'
end
is this even possible or would each form have to be dealt with individually?
Thanks
There are several stages I'd go through to refactor this code.
1. Extract the things that are changing (and make them more Rubyish)
post '/' do
require 'pony'
from = params[:name] || params[:subscribe]
subject = "#{params[:name]} has contacted you via the Website" ||
"#{params[:subscribe]} has subscribed to the newsletter"
body = "#{params[:email]}#{params[:comment]}"
Pony.mail(
:from => from,
:to => 'myemailaddress',
:subject => subject,
:body => body,
:via => :smtp,
:via_options => {
:address => 'smtp.gmail.com',
:port => '587',
:enable_starttls_auto => true,
:user_name => 'myemailaddress',
:password => 'mypassword',
:authentication => :plain,
:domain => "localhost.localdomain"
})
redirect '/success'
end
2. Make clear your intentions
in this case, that there are two branches through the code.
post '/' do
require 'pony'
if params[:name] # contact form
from = params[:name]
subject = "#{params[:name]} has contacted you via the Website"
else # subscription form
from = params[:subscribe]
subject = "#{params[:subscribe]} has subscribed to the newsletter"
end
body = "#{params[:email]}#{params[:comment]}"
Pony.mail(
:from => from,
:to => 'myemailaddress',
:subject => subject,
:body => body,
:via => :smtp,
:via_options => {
:address => 'smtp.gmail.com',
:port => '587',
:enable_starttls_auto => true,
:user_name => 'myemailaddress',
:password => 'mypassword',
:authentication => :plain,
:domain => "localhost.localdomain"
})
redirect '/success'
end
(I'm not a big fan of setting local vars within conditional branches, but we'll ignore that for clarity. I'd probably create a hash before the conditional with the keys already done, and then populate it in the branches but YMMV.)
3. Extract what doesn't change from what does.
Sinatra has a configure block just for this kind of thing.
require 'pony'
configure :development do
set :email_options, {
:via => :smtp,
:via_options => {
:address => 'smtp.gmail.com',
:port => '587',
:enable_starttls_auto => true,
:user_name => 'myemailaddress',
:password => 'mypassword',
:authentication => :plain,
:domain => "localhost.localdomain"
}
end
Pony.options = settings.email_options
Notice I've added :development as you may want to set it up differently for production.
Now your route is a lot cleaner and easier to debug:
post '/' do
if params[:name] # contact form
from = params[:name]
subject = "#{params[:name]} has contacted you via the Website"
else # subscription form
from = params[:subscribe]
subject = "#{params[:subscribe]} has subscribed to the newsletter"
end
body = "#{params[:email]}#{params[:comment]}"
Pony.mail
:from => from,
:to => 'myemailaddress',
:subject => subject,
:body => body,
redirect '/success'
end
My last tip, would be to put as many of those Pony options into ENV vars, which will not only keep things like passwords out of source control but also allow you to change the settings a lot easier. Perhaps put them in a Rakefile and load different environments for different contexts etc.
To use environment variables, I do the following:
# Rakefile
# in this method set up some env vars
def basic_environment
# I load them in from a YAML file that is *not* in source control
# but you could just specify them here
# e.g. ENV["EMAIL_A"] = "me#example.com"
end
namespace :app do
desc "Set up the environment locally"
task :environment do
warn "Entering :app:environment"
basic_environment()
end
desc "Run the app locally"
task :run_local => "app:environment" do
exec "bin/rackup config.ru -p 4630"
end
end
# from the command line, I'd run
`bin/rake app:run_local`
# in the Sinatra app file
configure :production do
# these are actual settings I use for a Heroku app using Sendgrid
set "email_options", {
:from => ENV["EMAIL_FROM"],
:via => :smtp,
:via_options => {
:address => 'smtp.sendgrid.net',
:port => '587',
:domain => 'heroku.com',
:user_name => ENV['SENDGRID_USERNAME'],
:password => ENV['SENDGRID_PASSWORD'],
:authentication => :plain,
:enable_starttls_auto => true
},
}
end
# then a block with slightly different settings for development
configure :development do
# local settingsā€¦
set "email_options", {
:via => :smtp,
:via_options => {
:address => 'smtp.gmail.com',
:port => '587',
:enable_starttls_auto => true,
:user_name => ENV["EMAIL_A"],
:password => ENV["EMAIL_P"],
:authentication => :plain,
:domain => "localhost.localdomain"
}
}
end
I usually keep most of these setting in a YAML file locally for development, but add these to the production server directly. There are lots of ways to handle this, YMMV.

Why am I getting =0A inside emails being sent, where there should be a line break?

I'm getting =0A inside my emails where there should be a line break.
#article = DB[:posts][:nodeview_id => view, :nodeview => 'article']
Pony.mail(:html_body => #article[:content], :reply_to => #email, :subject => "New article #{#article[:title]}", :headers => { "X-MC-Tags" => "feedback" } )
And ##article[:content]} in this context, is
apples
bananas
inside the database, no \n or <br> tags.
Here's how Pony is configured.
Pony.options = { :from => 'Compesh <donotreply#compesh.com>', :to => 'blahblahblah#emails.com',
:via => :smtp, :via_options => {
:address => 'smtp.mandrillapp.com', :port => '587',
:user_name => 'XXX', :password => 'XXXXXX'
},
:headers => { "X-MC-AutoText" => "yes" }, :charset => 'utf-8'
}
But in my emails I get
apples=0Abananas
Pony doesn't let me choose the content type, I don't think.
I managed to fix this by converting newlines to a <br> tag. It turns out it had nothing to do with the content type or encoding of the email at a..
mystring.gsub(/(?:\n\r?|\r\n?)/, '<br>')
This specially general regex function, has a way of covering DOS, *NIX, Mac and accidental invalid line endings.

Resources