I've created a Rake Task for a Mailer to later scheduled wth Crontab and automate with Gem Whenever for send a email to a users. For a while is a just a test to know if task is working.
My Rake Task and Mailer is the following.
require 'rake'
desc 'send digest email'
task send_warn_course: :environment do
MailCourseWarnMailer.course_available(user).deliver!
end
# And my Mailer is:
class MailCourseWarnMailer < ActionMailer::Base
def course_available(user)
@user = user
mail(to: @user.email, subject: "Curso disponível")
end
end
I passed the parameters to task but this is not working. When I run rake send_warn_course
I get the error:
rake send_warn_course
rake aborted!
NameError: undefined local variable or method `user' for main:Object
Anyone knows what is happening? What did I miss here?
As the error suggests you don't have User
defined.
You need to input email ID or ID of the user and need to find the user from the database and then pass it to the function.
Something like the following:
require 'rake'
desc 'send digest email'
task :send_warn_course, [:user_email] => :environment do |t, args|
user = User.find_by_email args[:user_email]
MailCourseWarnMailer.course_available(user).deliver!
end
# And my Mailer is:
class MailCourseWarnMailer < ActionMailer::Base
def course_available(user)
@user = user
mail(to: @user.email, subject: "Curso disponível")
end
end
Then, you can run the task like:
rake send_warn_course['[email protected]']
As it is a scheduler task you might not want to pass a variable with each task and instead would like to perform some database queries to find the relevant users. But this was just to demonstrate the fix of the error.