jeudi 2 juillet 2015

Rake task can't load ActionMailer records from Rails.cache "ArgumentError: undefined class/module ApplicationMailer"

I want to generate an email list that deliver the emails later using the whenever gem and rake tasks.

namespace :email_reminder do
  task create_user_list: :environment do
    redis_hash = {}
    User.where(XXX).each do |user|
      items_to_remind = Item.where(XXX)
      redis_hash[user.id] = items_to_remind
    end
    redis_hash["updated_at"] = Time.now
    $redis.set "saved_email_list", redis_hash.to_json
  end

  task create_email_array: :environment do
    data = JSON.parse($redis.get("saved_email_list"))
    email_array = []
    data.each do |k,v|
        ### Access records user, items array ###
        email_array << ApplicationMailer::items_reminder(user, items)
    end
    Rails.cache.write("items_reminder_emails", email_array)
  end

  task deliver_emails: :environment do
    Rails.cache.read("items_reminder_emails").map { |e| e.deliver }
  end
end

Everything works find except I get an error in the last rake task when trying to access the Rails.cache. If I run the same code in rails console there is not problem.

rake aborted!
ArgumentError: undefined class/module ApplicationMailer

Additional Question: Is there a better way to do this? Can I store the AppMailer records in Redis?

Aucun commentaire:

Enregistrer un commentaire