rake task can't access rails.cache

2019-07-17 17:37发布

问题:

I want to call a rake task from a cron job that stores remote weather data in the rails cache. However, I must be doing something pretty wrong here because I cannot find any solution through countless fruitless searches.

Say I define and call this task

namespace :weather do
  desc "Store weather from remote source to cache"
  task :cache do
    Rails.cache.write('weather_data', Date.today)
  end
end

I get the error

Anonymous modules have no name to be referenced by

Which leads me to believe the rails cache isn't available. Outputting Rails.class from the rake file gives me Module but Rails.cache.class again returns the above error. Do I need to include something here? Am I just hopeless at internet? :)

Thanks in advance.

回答1:

try passing in the rails environment

task (:cache => :environment) do
    ...
end

seems like you would get a different error, but I would try this