1

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

7 Comments

How Can I do this? Directly in Mailer? Thanks.
I didn't get about what you're asking?
Sorry, I asked without having seen the update of his answer. Now it's working, but I need that this be automatic, in a way that when run rake send_warn_course the Rake Task send to all of users in my DB. I'm trying here, but by chance, you have some tip for me about? Thanks. :D
Well, I am interested in what you come up with! :)
How can I get in the emails from my DB in this task? I'm trying but no success :/
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.