0

Upon following the instructions to create a rake task to clear the cache, when running that rake task:

namespace :cache do desc "Clears Rails cache" task :clear do Rails.cache.clear end end 

and running that rake task with:

rake cache:clear 

I get an error:

undefined method `clear' for nil:NilClass 

When running Rails.cache.clear from the rails console, it successfully clears the cache without an error. Why is cache nil on the Rails object in the rake task, but not in the rails console?

Note: I am using dalli and memcache.

2 Answers 2

2

To answer Why is => :environment needed?

:environment is a task defined by rails. When you need to interact with your application models, perform database queries and so on, your custom task should depend on the environment task, as it will load your rails application code.

Rails.cache will return nil if your application is not loaded. Hence, the error undefined method 'clear' for nil:NilClass

You need to run environment task before your custom clear task.

namespace :cache do desc "Clears Rails cache" task :clear => :environment do ## This will run environment task first and then clear task Rails.cache.clear end end 
Sign up to request clarification or add additional context in comments.

Comments

0

Figured it out. I was missing => :environment after :clear

The below works:

namespace :cache do desc "Clears Rails cache" task :clear => :environment do Rails.cache.clear end end 

Why is => :environment needed?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.