Question

I want to run a rake task, but it's complaining about not having the devise secret key. I was hoping defining the task with task :mytask => :environment would have loaded that up for me but I would need to specify it when calling the rake task.

I keep my secret key in .env-production and normally source the file then export DEVISE_SECRET_KEY. But I don't want to have to type source .env-production && export DEVISE_SECRET_KEY && RAILS_ENV=production rake mytask just to run a rake task.

I tried to enhance the :environment task like so:

# lib/tasks/environment.rake
Rake::Task["environment"].enhance do
  if Rails.env.production?
    fn = ".env-production"
  else
    fn = ".env"
  end

  puts "Trying to read devise secret key from #{fn}"

  match = File.read(fn).match /DEVISE_SECRET_KEY="(.*)"/

  if match
    Devise.secret_key = match[1]
    ENV['DEVISE_SECRET_KEY'] = match[1]
    puts "Found devise secret key"
  else
    puts "Couldn't find secret key"
  end
end

But it still complains about not knowing the key... is there any way to make this work?

Was it helpful?

Solution

Man, the answer was simple.

I just changed it to this:

task :load_devise_key do
  if Rails.env.production?
    fn = ".env-production"
  else
    fn = ".env"
  end

  puts "Trying to read devise secret key from #{fn}"

  match = File.read(fn).match /DEVISE_SECRET_KEY='(.*)'/

  puts File.read(fn)
  if match
    Devise.secret_key = match[1]
    ENV['DEVISE_SECRET_KEY'] = match[1]
    puts "Found devise secret key"
  else
    puts "Couldn't find secret key"
  end
end

task :environment => :load_devise_key

Seems to have done the trick!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top