From 708d1398b1b5a373e6519658990c113c536e3006 Mon Sep 17 00:00:00 2001 From: Cristian Mircea Messel Date: Wed, 3 Sep 2014 16:36:58 +0300 Subject: [PATCH] Convert x-smtpapi params to json only if needed This will ensure the gem does not break the code of existing users for the gem --- lib/sendgrid_toolkit/mail.rb | 12 ++++++++++-- spec/lib/sendgrid_toolkit/mail_spec.rb | 7 +++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/lib/sendgrid_toolkit/mail.rb b/lib/sendgrid_toolkit/mail.rb index 1dfd19a..c54dd8c 100644 --- a/lib/sendgrid_toolkit/mail.rb +++ b/lib/sendgrid_toolkit/mail.rb @@ -10,8 +10,16 @@ def send_mail(options = {}) private def convert_params(options) - options["x-smtpapi"] = options["x-smtpapi"].to_json if options.has_key?("x-smtpapi") - options + if options.has_key?("x-smtpapi") && !x_smtpapi_parsable_json?(options) + options["x-smtpapi"] = options["x-smtpapi"].to_json + end + options + end + + def x_smtpapi_parsable_json? options + !!JSON.parse(options["x-smtpapi"]) + rescue + false end end end diff --git a/spec/lib/sendgrid_toolkit/mail_spec.rb b/spec/lib/sendgrid_toolkit/mail_spec.rb index 4421843..79ff2bc 100644 --- a/spec/lib/sendgrid_toolkit/mail_spec.rb +++ b/spec/lib/sendgrid_toolkit/mail_spec.rb @@ -20,5 +20,12 @@ response = @obj.send_mail :to => "scottb@sendgrid.com", :from => "testing@fiverr.com", :subject => "Subject", :text => "Text", "x-smtpapi" => xsmtpapi response.request.options[:query]["x-smtpapi"].should == xsmtpapi.to_json end + + it "only converts x-smtpapi to json if it has not been converted yet" do + FakeWeb.register_uri(:post, %r|https://#{REGEX_ESCAPED_BASE_URI}/mail\.send\.json\?|, :body => '{"message":"success"}') + xsmtpapi = {:category => "Testing", :to => ["scottb@sendgrid.com"]}.to_json + response = @obj.send_mail :to => "scottb@sendgrid.com", :from => "testing@fiverr.com", :subject => "Subject", :text => "Text", "x-smtpapi" => xsmtpapi + response.request.options[:query]["x-smtpapi"].should == xsmtpapi + end end end