NoMethodError Ruby 1.9.3 - ruby-on-rails

I am using Ruby 1.9.3 and getting the following error on the following line while trying to use the SendGrid API.
ERROR [on this line below "mailer.mail(mail_defaults)"]:
NoMethodError (undefined method `to_h' for #<Hash:0x00000005da0958>):
CODE:
assuming some users
recipients = []
recipient = SendGrid::Recipient.new('jn#geo.com')
recipient.add_substitution('name', 'Billy Bob')
recipient.add_substitution('number', 1234)
recipient.add_substitution('time', '10:30pm')
recipients << recipient
# then initialize a template
template = SendGrid::Template.new('blahblah7bef2-d25b00')
# create the client
# see client above
# set some defaults
mail_defaults = {
:from => 'no-reply#geo.com',
:html => '<h1>I like email tests</h1>',
:text => 'I like email tests',
:subject =>'Test Email is great',
}
mailer = SendGrid::TemplateMailer.new(client, template, recipients)
# then mail the whole thing at once
mailer.mail(mail_defaults)
I thought it might be my mail_defaults array so I tried this (see below) and received the same error on the same line.
mail_defaults = {
from: 'no-reply#geo.com',
html: '<h1>I like email tests</h1>',
text: 'I like email tests',
subject: 'Test Email is great',
}
Do I have an error in my code or is their an error in SendGrids mailer.mail method?

This problem is with mail.mailer. This uses the to_h method internally, which was implemented in Ruby 2.1. Effectively, the sendgrid sdk requires ruby 2.1 now. I had the same issue with Ruby 1.9.3 and solved it by upgrading to 2.1.
This is what I used to upgrade to Ruby 2.1 on CentOS 6 (not my gist):
https://gist.github.com/mustafaturan/8290150
Hope this helps.

Related

Undefined method `escape' for URI:Module

I'm a noob studying Ruby on Rails. I am trying to integrate my ruby on rails app to Quickbooks. I'm following the steps of this video. And I am stuck when I try to authenticate by pressing the "Connect to QuickBooks" button.
I get this error;
I did a little research and found out that this error was about the URI.escape() command. I think they removed it in Ruby 3. How can I resolve this issue? I can't even figure out where this URI.escape() command is located.
This is from vendors_controller.rb
def authenticate
callback = oauth_callback_vendors_url
token = $qb_oauth_consumer.get_request_token(:oauth_callback => callback)
session[:qb_request_token] = token
# If Rails >= 4.1 you need to do this => session[:qb_request_token] = Marshal.dump(token)
redirect_to("https://appcenter.intuit.com/Connect/Begin?oauth_token=#{token.token}") and return
end
def oauth_callback
at = session[:qb_request_token].get_access_token(:oauth_verifier => params[:oauth_verifier])
# If Rails >= 4.1 you need to do this => at = Marshal.load(session[:qb_request_token]).get_access_token(:oauth_verifier => params[:oauth_verifier])
session[:token] = at.token
session[:secret] = at.secret
session[:realm_id] = params['realmId']
redirect_to root_url, notice: "Your QuickBooks account has been successfully linked."
end
My initializer quickbooks.rb
QB_KEY = "I PASTED MY CLIENT ID KEY HERE"
QB_SECRET = "I PASTED MY CLIENT SECRET HERE"
$qb_oauth_consumer = OAuth::Consumer.new(QB_KEY, QB_SECRET, {
:site => "https://oauth.intuit.com",
:request_token_path => "/oauth/v1/get_request_token",
:authorize_url => "https://appcenter.intuit.com/Connect/Begin",
:access_token_path => "/oauth/v1/get_access_token"
})
My rails version Rails 6.1.4
My ruby version ruby 3.0.1p64
Thank you for your time.
I know many people say that URI.escape wasn't good, but it was good enough for me when all I wanted from it is to escape urls with non-English characters.
So I just monkey patched it
Add the following under /config/initializers/functions_overrides.rb
(the file name can be anything you want)
require 'uri'
module URI
class << self
def escape(str)
alpha = "a-zA-Z"
alnum = "#{alpha}\\d"
unreserved = "\\-_.!~*'()#{alnum}"
reserved = ";/?:#&=+$,\\[\\]"
unsafe = Regexp.new("[^#{unreserved}#{reserved}]")
str.gsub(unsafe) do
us = $&
tmp = ''
us.each_byte do |uc|
tmp << sprintf('%%%02X', uc)
end
tmp
end.force_encoding(Encoding::US_ASCII)
end
end
end
Use the https://developer.intuit.com/app/developer/qbo/docs/develop/sdks-and-samples-collections/ruby
OAuth Ruby Client
Intuit offers an OAuth 2.0 Client which provides a set of methods that make it easier to work with Intuit’s OAuth and OpenID implementation.
Community Supported Ruby SDK
The Community Supported Ruby SDK makes it easy to integrate your web app with the QuickBooks Online API. This guide assumes that you have an existing web app that you want to integrate with QuickBooks Online.
URI#escape was deprecated and later removed - https://github.com/ruby/uri/commit/61c6a47ebf1f2726b60a2bbd70964d64e14b1f98
From the commit :
# This method is obsolete and should not be used. Instead, use
# CGI.escape, URI.encode_www_form or URI.encode_www_form_component
# depending on your specific use case.
Ruby 3.0.0 onwards URI#escape does not work.
Use CGI.escape or URI.encode_www_form as mentioned in the deprecation warning

ActionMailer::Base::NullMail when trying exception_notification in development

I'd like to add the exception_notification gem to our app, however, this happens when I try to manually trigger a mail:
exception
# => #<ZeroDivisionError: divided by 0>
ExceptionNotifier::Notifier.exception_notification(request.env, exception)
# => #<ActionMailer::Base::NullMail:0x007fa81bc7c610>
ExceptionNotifier::Notifier.background_exception_notification(exception)
# => #<ActionMailer::Base::NullMail:0x007fa81bf58190>
In the above example, the console is at a breakpoint inside rescue_from Exception in the ApplicationController after a deliberate 1/0 in some controller.
I'm using delayed_job as well, but - no surprise - ExceptionNotifier::Notifier.background_exception_notification(exception).deliver does not spool anything.
I've already set config.consider_all_requests_local = false in development, but still exception_notification instantiates NullMail. In other parts of the app, mailers work just fine and use sendmail.
Any ideas what I'm doing wrong here? Thanks for your help!
Likely you are using an old version of the ExceptionNotifier and a newer version of ActiveMailer::Base. Not calling the mail command within the email functionality will result in the ActionMailer::Base::NullMail instance returned rather than a Mail instance.
From documentation:
class Notifier < ActionMailer::Base
default :from => 'no-reply#example.com',
:return_path => 'system#example.com'
def welcome(recipient)
#account = recipient
mail(:to => recipient.email_address_with_name,
:bcc => ["bcc#example.com", "Order Watcher <watcher#example.com>"])
end
end
I had my tests / rspec returning NullMail objects. the solution was simple, my code was:
def my_mail(foo)
mail(
to: to,
from: from,
subject: #sample_item.campaign_market.campaign.translation_for(language_id, 'sample_item_mailer.request_review.subject'),
content_type: "text/html"
)
#sample_item.update_attributes!({feedback_requested: true, review_requested_at: Time.now})
TrackingService::Event.new(#user, #user.market, 'sample_items', "request_review_email #{#sample_item.id}").call()
end
what's not immediately clear from the ruby docs is that you need to return the mail function,not just execute it. If you need to do something after building the mail object make sure you return the mail at the end. like so:
def my_mail(foo)
m = mail(
to: to,
from: from,
subject: #sample_item.campaign_market.campaign.translation_for(language_id, 'sample_item_mailer.request_review.subject'),
content_type: "text/html"
)
#sample_item.update_attributes!({feedback_requested: true, review_requested_at: Time.now})
TrackingService::Event.new(#user, #user.market, 'sample_items', "request_review_email #{#sample_item.id}").call()
return m
end

Rails: Amazon aws-ses, missing required header 'From'

Email from Ruby code is sending without any issue. But when I try to send it from Rails console, it gives the Missing required header 'From' error even From is specified in the email (Notifier), see below:
def send_email(user)
recipients "#{user.email}"
from %("Name" "<name#domain.com>")
subject "Subject Line"
content_type "text/html"
end
Here is email sending code from rails console:
ActionMailer::Base.delivery_method = :amazon_ses
ActionMailer::Base.custom_amazon_ses_mailer = AWS::SES::Base.new(:secret_access_key => 'abc', :access_key_id => '123')
Notifier.deliver_send_email
Am I missing something?
GEMS used: rails (2.3.5), aws-ses (0.4.4), mail (2.3.0)
Here is how it was fixed:
def send_email(user)
recipients "#{user.email}"
from "'First Last' <name#domain.com>" # changing the FROM format fixed it.
subject "Subject Line"
content_type "text/html"
end

Rails 2 - sending pdf via emailer

I'm using ruby 1.8.7, rails 2.3.4, rubygems 1.3.6, windows 7 home basic.
Objective: to convert a html page into pdf and send it via email. (like an online receipt)
Here's what i used: prawn (for pdf) emailer (for email)
question: how to do i send an email to a real email address? All i got from the tutorial is sending an "email" that can be seen in command prompt. that's all. another question is how to generate pdf's on the fly, meaning there should be no file generated and attach it to an email? It's really hard and I have been working on this for weeks now. thanks.
The precise answer to your question depends on precisely how you're generating your pdfs, but here's an example that should work:
1) In your controller file (as part of an action)
pdf_doc = Prawn::Document.new()
pdf.text "Hello, world" # etc, etc
data_string = pdf_doc.render
user = 'me#example.com'
Emailer.deliver_email_with_attachment(user,data_string)
2) In your mailer file (e.g. app/models/emailer.rb)
class Emailer < ActionMailer::Base
def email_with_attachment(user, data)
# setup your email as normal using #from, #subject, etc
#from = user
# now attach the pdf
attachment :content_type => "application/pdf", :body => data
end
end
for more information on attachments in ActionMailer see The rails docs
EDIT: You should also make sure you've edited your config file(s) to make sure your rails app can send emails. As you're using windows you'll need to configure sending by SMTP:
config/environments/development.rb
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:address => "my.smtp-server.com",
:port => 25,
:domain => 'iwantgreatcare.org',
:user_name => 'username',
:password => 'password',
:authentication => 'plain',
}
For more information on configuring smtp setting see the Rails ActionMailer guide

ActionMailer 3 error - undefined method `encode!' for "Welcome":String

I'm getting this error while sending mail to the registered user in rails 3:
undefined method 'encode!' for "Welcome":String
I have the following code
#content = content
mail(:to => content[:email], :subject => "test")
If there is a subject then above error message displaying, if I remove the subject content
#content = content
mail(:to => content[:email], :subject => "") no error message sending with out subject
I'm using:
Rails version 3.0.1
action mailer 3.0.1
mail gem checks for Encoded global constant. If its defined by any gem or your code then it calls encode! on the mail object. Here is this call from UnstructuredField mail gem class:
def encode(value)
value.encode!(charset) if defined?(Encoding) && charset
(value.not_ascii_only? ? [value].pack("M").gsub("=\n", '') : value).gsub("\r", "=0D").gsub("\n", "=0A")
end
For me it was mail subject, a String, so I monkey patched String:
class String
def encode!(value)
#Do any encoding or simply return it
value
end
end
Try using ruby version 1.9
I got this error while using devise with rails 3.0.3 and ruby 1.8.7.
I migrated to ruby 1.9 and it worked like a charm.

Resources