How to view the html and text generated by Active - ruby-on-rails

I don't want to actually send the email, I just want to be able to view the email that action mailer generates for both the HTML and TEXT email types.
So something like:
html = UserMailer.welcome_email(#user).html
text = UserMailer.welcome_email(#user).text
Is this possible?
Update
I am trying this backport render out: https://github.com/brainopia/backport_new_renderer/blob/master/backport_new_renderer.rb
I have this so far:
class EmailController < ActionController::Base
layout "email"
def welcome
end
end
My /app/views/email/welcome.html.erb is just:
Hello <%= #name %>
Then I created a lib/rasks/render.rake file that looks like:
desc "testing controller rendering backport"
task :render do
puts "hello render"
#name = "adf"
EmailController.render(:welcome)
end
error is:
hello render
rake aborted!
NameError: uninitialized constant EmailController
/Users/path/to/apps/myapp/lib/tasks/render.rake:5:in `block in <top (required)>'
Tasks: TOP => render
(See full trace by running task with --trace)

If you are using Rails 5, you can render a template using:
ActionController.render('mailer/mymailer.html.erb', assigns: { a: b })
But as the poster above mentioned, you likely just want to preview the email. The letter_opener gem is good. I recently discovered and love Mailcatcher.

Presumably you want this so you can validate the appearance of the email.
There is a gem written by the creator of RailsCasts Ryan Bates called letter_opener.
It lets you set the delivery method in development as :letter_opener (instead of :smtp or anything else) and when an email is sent by your app a browser window opens showing you the content and layout of your email.
https://github.com/ryanb/letter_opener

Related

Rails "noticed gem" saying uninitialized constant

I am trying to get notifications to work in my app. I found "noticed gem" from this GitHub repo and followed all the steps that he does. I have the gem in my gem file, I did bundle install and update and rails db:migrate and everything. However when I try running this in rails console
CommentNotification.with(post: #post).deliver(current_user)
I get
Traceback (most recent call last):
1: from (irb):1
NameError (uninitialized constant CommentNotification)
This is my comment_notification.rb class that gets generated under app/notifications/comment_notificaiton.rb when I run rails generate noticed:notification CommentNotification just as he does in the video and just as the documentation suggests.
# To deliver this notification:
#
CommentNotification.with(post: #post).deliver_later(current_user)
CommentNotification.with(post: #post).deliver(current_user)
class CommentNotification < Noticed::Base
# Add your delivery methods
#
deliver_by :database
# deliver_by :email, mailer: "UserMailer"
# deliver_by :slack
# deliver_by :custom, class: "MyDeliveryMethod"
# Add required params
#
param :post
# Define helper methods to make rendering easier.
#
def message
t(".message")
end
#
def url
post_path(params[:post])
end
end
You have to restart your spring server.
Using bin/spring stop command, the spring server will be stopped. Then the server will be started using rails server or rails s.
A bit late to this, but manually loading the notification class in rails console solved this issue in my case, i.e.: load "app/notifications/comment_notification.rb". (PS: I would also check the spelling of the file name, i.e. comment_notification vs comment_notificaiton)
Uncomment the first two lines:
# CommentNotification.with(post: #post).deliver_later(current_user)
# CommentNotification.with(post: #post).deliver(current_user)
remember, #post must be the resource that you are going to store in user notifications
user.notifications
#post must exist

How to protect visible email address from spam with gem for Ruby 4?

I'd like to obfuscate an email address on my webpage. I'm hoping to avoid JS in case my users deactivate it.
I found this gem: actionview-encoded_mail_to but it doesn't seem to work for me. It shows the full email address on the page (which is good), but it also shows it in the console.
I tried the 3 examples with the same result. The gem appears in my Gemfile so should be correctly installed.
You can always roll your own but, first, that gem definitely works. Here's what I did...
Using the Gem
I added the gem to a Rails 4.2 app:
# Gemfile
gem 'actionview-encoded_mail_to'
I installed it:
$ bundle install
I entered the console:
$ rails console
I made the helper methods available in the console:
include ActionView::Helpers::UrlHelper
Called the mail_to helper with the same arguments as the example:
mail_to "me#domain.com", nil, replace_at: "_at_", replace_dot: "_dot_", class: "email"
...and got this result:
"<a class=\"email\" href=\"mailto:me#domain.com\">me_at_domain_dot_com</a>"
That "me_at_domain_dot_com" looks properly obfuscated. What steps did you take?
Rolling your own obfuscation
It would be a trivial string substitution to obfuscate an email string, we can just use sub:
def obfuscate_email(email, replace_at: '_at_', replace_dot: '_dot_')
email.sub("#", replace_at).sub ".", replace_dot
end
I tested that out in the console:
obfuscate_email "me#example.com"
# => "me_at_example_dot_com"
You can place that method in application_helper.rb and use it in any of your views:
link_to obfuscate_email(user.email), "mailto:#{user.email}"
# => "me_at_example_dot_com"
Note that the href must be the unobfuscated email in order for it to work properly.
Towards a more complete mail_to helper
def obfuscated_mail_to(email, options = {})
link_to obfuscate_email(email), "mail_to:#{email}", options
end
Testing that in the console:
obfuscated_mail_to "me#example.com", class: "email"
=> "<a class=\"email\" href=\"mail_to:me#example.com\">me_at_example_dot_com</a>"
Hope that helps!

Resque Mailer fails to send email due to wrong number of arguments

I'm a Rails newbie, so please forgive any ignorance on my part. The issue I'm having is that I have a Resque job setup to send an email. I have the job running, but it produces an error:
Unable to deliver email [send_daily_digest_email]: wrong number of arguments (given 2, expected 0)
I get this same error when I try to test the mailer from console...
TicketMailer.send_daily_digest_email("emailaddress#domain.com").deliver_now
Here is the mailer code:
class TicketMailer < ActionMailer::Base
layout 'mailer'
include Resque::Mailer
default :from => 'test <test#ignore.com>'
def send_daily_digest_email(email)
mail(:to => email, :subject => 'test')
end
end
What am I doing wrong? Where should I look to figure this out? Thanks!
As noted in the comments, the issue was due to Rails 5 not being fully supported in the current release of the resque-mailer gem. Support is built in now, but I had to pull from master on the repo:
gem "resque_mailer", :git => "https://github.com/zapnap/resque_mailer.git"

Rspec tests failing when using amazon ses mail sending

I recently switched over a rails app to send mail through amazon ses. The sending of the mail works fine, however the tests are failing around the mail items with the following error:
TypeError:
can't convert Fixnum into String
# (eval):3:in 'send_raw_email'
I have the test environment mail settings set properly to :test
config.action_mailer.delivery_method = :test
I can prevent the errors from happening by not sending emails, but then I get errors about the mail not being delivered.
config.action_mailer.perform_deliveries = false
should_change -> { ActionMailer::Base.deliveries.size } do
result should have changed, but is still 0
Gem versions are below:
rails (3.2.12)
rspec (2.8.0)
cucumber (2.3.3)
aws-sdk (1.33.0)
Any suggestions on what is going on, or how to work around this. If any other info is needed let me know. This worked fine before I switched the sending of mail to use amazon ses.
EDIT:
The tests that are failing, are all that involve an email being sent using .deliver
BlahMailer.send_invite(team).deliver
This is inside a model and controller which the tests just call the associated route in the controller or call the associated function in the model. Not sure what else to show, since the error is showing its coming from send_raw_email which is the ses function, not any code from the app.
EDIT 2: More code
Here is one of the tests, in this example it sets up the factory for the model and each test.
before :each do
subject = Factory(:ticket, action_type: 'name_change', team_name: 'test123')
end
Here is the factory in rspec
Factory.define :ticket do |ticket|
team = nil
ticket.team { team = Factory(:team) }
ticket.creator { team.captain }
ticket.subject { Factory(:team_assignment, team: team, user: Factory(:active_user)).user }
end
And then here is the code in the model around where the email is sent
%w(requested approved cancelled accepted).each do |state|
define_method "notify_#{state}" do
TicketMailer.send("#{action_type}_#{state}", self).deliver
end
end
I have tried putting in straight text for basically everything having to do with the mailer, just to make sure there are no issues with that. If you need anymore of the model or the actual mailer let me know. I just really cant figure out where this is dieing. My only conclusion is its just a bug with the older versions of the aws sdk and rspec gems. I even tried replacing aws-sdk with newer versions but was still unsuccessful in getting anything else to work.
The problem is that you're setting config.action_mailer.perform_deliveries = false, so no deliveries are being made and therefore ActionMailer::Base.deliveries will always be an empty collection.
If you want to test email deliveries, then set config.action_mailer.perform_deliveries = true and use an interceptor to ensure you're not sending emails to users.
lass SandboxEmailInterceptor
def self.delivering_email(message)
recipients =
if Rails.env.test?
[
"user#example.com"
]
end
message.to = recipients
message.cc = []
end
end
unless Rails.env.production? || Rails.env.test?
ActionMailer::Base.register_interceptor(SandboxEmailInterceptor)
end

Delayed_job in rails failing

I am just beginning to look into using the delayed_job gem.
To test it, I added "delayed" to the welcome email function and changed that call from
UserMailer.welcome_email(self).deliver
to
UserMailer.delay.welcome_email(self)
This is called inside the User model after_create. I see an entry show up in the delayed_job table after the function executes. Now when I run "rake jobs:work" on command line the task starts but gives errors as below
[Worker(host:Sanjay-PC pid:7008)] Starting job worker
[Worker(host:Sanjay-PC pid:7008)] Class#welcome_email failed with NoMethodError: undefined method `welcome_email' for #<Class:0x4871d60> - 0 failed attempts
[Worker(host:Sanjay-PC pid:7008)] 1 jobs processed at 0.0939 j/s, 1 failed ...
Thinking that if I changed the welcome_email method declaration to a Class method as
def self.welcome_email(user)
(added self. in front) that might help. But then when I run rake jobs:work I get the following error
rake aborted!
undefined method `welcome_email' for class `UserMailer'
C:/Ruby192/lib/ruby/gems/1.9.1/gems/activesupport-3.0.5/lib/active_support/core_ext/module/aliasing.rb:31:in `alias_method'
C:/Ruby192/lib/ruby/gems/1.9.1/gems/activesupport-3.0.5/lib/active_support/core_ext/module/aliasing.rb:31:in `alias_method_chain'
C:/Ruby192/lib/ruby/gems/1.9.1/gems/delayed_job-2.1.4/lib/delayed/message_sending.rb:50:in `handle_asynchronously'
c:/mgn/mgn-r3/app/mailers/user_mailer.rb:10:in `<class:UserMailer>'
c:/mgn/mgn-r3/app/mailers/user_mailer.rb:1:in `<top (required)>'
C:/Ruby192/lib/ruby/gems/1.9.1/gems/activesupport-3.0.5/lib/active_support/dependencies.rb:454:in `load'
<Stack truncated>
It seems to now know the class as UserMailer but it somehow doesn't see the class method welcome_email.
I am on Rails 3.0.5, Ruby 1.9.2p180 and the installed delayed_job gem is 2.1.4 - on Windows
Can't seem to find any related answers anywhere.
Thanks for your thoughts.
-S
Adding UserMailer code per #pjammer's request
class UserMailer < ActionMailer::Base
default :from => "from#example.com"
def welcome_email(user)
#user = user
#url = "http://example.com/login"
mail(:to => user.email,
:subject => "Welcome to My Awesome Site")
end
end
Just use this
UserMailer.delay.welcome_email(self).deliver
instead of
UserMailer.welcome_email(self).delay.deliver
My solution was to redefine function at the handler class (for you it's UserMailer class)
def self.taguri
'tag:ruby.yaml.org,2002:class'
end
It's a hack and I'll try to find a better solution but now it works for me.
(Rails 3.0.9, Ruby 1.9.2-p290, delayed_job 2.1.4)
https://groups.google.com/forum/?fromgroups=#!topic/delayed_job/_gvIcbXrOaE solved my handles_asynchronously error for class methods.
As per Brandon Keeper in the link above, the code is the following:
class ClassName
class << self
def foo
end
handle_asynchronously :foo
end
end
then use ClassName.delay.foo

Resources