如何在rake任务中设置Devise密钥

时间:2014-03-19 21:10:53

标签: ruby-on-rails devise rake environment-variables

我想执行一个rake任务,但它抱怨没有设计密钥。我希望用task :mytask => :environment定义任务会为我加载,但我需要在调用rake任务时指定它。

我将密钥保存在.env-production中,并且通常会将文件提供,然后导出DEVISE_SECRET_KEY。但我不想只是为了运行rake任务而输入source .env-production && export DEVISE_SECRET_KEY && RAILS_ENV=production rake mytask

我试图像这样增强:environment任务:

# 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

但它仍然抱怨不知道关键......有没有办法使这项工作?

1 个答案:

答案 0 :(得分:0)

男人,答案很简单。

我刚把它改成了这个:

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

好像已经成功了!