2015-07-10 128 views
1

我跑我的任務箱DB:恢復並顯示錯誤:Rspec的 - 未初始化的常量RAILS_ENV

** Execute db:restore 
rake aborted! 
NameError: uninitialized constant RAILS_ENV 
/home/dima/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/rspec-core-2.5.2/lib/rspec/core/backward_compatibility.rb:20:in `const_missing' 
/home/dima/myapp/bdsmgalaxy/lib/tasks/mysql.rake:24:in `block (2 levels) in <top (required)>' 

我的任務是:

require 'yaml' 

namespace :db do 
    def backup_prep 
    @directory = File.join(RAILS_ROOT, 'db', 'backup') 
    @db = YAML::load(File.open(File.join(RAILS_ROOT, 'config', 'database.yml')))[ RAILS_ENV ] 
    @db_params = "-u #{@db['username']} #{@db['database']}" 
    @db_params = "-p#{@db['password']} #{@db_params}" unless @db['password'].blank? 
    end 

    desc 'Backup database by mysqldump' 
    task :backup => :environment do 
    backup_prep 
    FileUtils.mkdir @directory unless File.exists?(@directory) 
    file = File.join(@directory, "#{RAILS_ENV}_#{DateTime.now.to_s}.sql") 
    command = "mysqldump #{@db_params} | gzip > #{file}.gz" #--opt --skip-add-locks 
    puts "dumping to #{file}..." 
    # p command 
    exec command 
    end 

    desc "restore most recent mysqldump (from db/backup/*.sql.*) into the current environment's database." 
    task :restore => :environment do 
    unless RAILS_ENV=='development'  
     puts "Are you sure you want to import into #{RAILS_ENV}?! [y/N]" 
     return unless STDIN.gets =~ /^y/i 
    end 
    backup_prep 
    wildcard = File.join(@directory, ENV['FILE'] || "#{ENV['FROM']}*.sql*") 
    puts file = `ls -t #{wildcard} | head -1`.chomp # default to file, or most recent ENV['FROM'] or just plain most recent 
    if file =~ /\.gz(ip)?$/ 
     command = "gunzip < #{file} | mysql #{@db_params}" 
    else 
     command = "mysql #{@db_params} < #{file}" 
    end 
    p command 
    puts "please wait, this may take a minute or two..." 
    exec command 
    end 
end 

如何解決這個問題呢?

+0

在你的boot.rb'RAILS_ENV'定義? – Saurabh

+0

你嘗試過'rake db:restore RAILS_ENV =「development」'? – CoupDeMistral

+0

@saurabh,不,不要在開機,rb。如何添加正確? – dev85

回答

2

RAILS_ENV是一個環境變量。你必須使用ENV['RAILS_ENV']

即:

unless ENV['RAILS_ENV']=='development' 
+0

謝謝,但現在顯示錯誤NoMethodError:未定義方法'[]'爲零:NilClass /home/dima/myapp/bdsmgalaxy/lib/tasks/mysql.rake:7:in'backup_prep' – dev85

+0

7行 - '@ db = YAML :: load(File.open(File.join(Rails.root,'config','database.yml')))[ENV ['RAILS_ENV']]' – dev85

相關問題