rake任务中的环境变化

时间:2011-11-28 09:41:27

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1

我正在使用 MySQL 数据库和mysql2 gem 开发 Rails v2.3 应用。我遇到了一个奇怪的情况,即 rake 任务中改变环境

(我对环境和数据库的所有设置和配置都是正确的,没问题。)

这是我的简单故事:

我有一个像下面这样的rake任务:

namespace :db do
   task :do_something => :environment do
       #1. run under 'development' environment
       my_helper.run_under_development_env

       #2. change to 'custom' environment 
       RAILS_ENV='custom'

       Rake::Task['db:create']
       Rake::Task['db:migrate']

       #3. change back to 'development' environment
       RAILS_ENV='development'

       #4. But it still run in 'customer' environment, why?
       my_helper.run_under_development_env 
   end

end

rake 任务非常简单,它的作用是:

1。首先,在“开发”环境下从my_helper运行方法

2. 然后,更改为“自定义”环境并运行db:createdb:migrate

直到现在,一切都很好,环境确实变为“自定义

3. 然后,再将其更改回“开发”环境

4. 在“开发”环境下再次运行辅助方法

但是,虽然我已在步骤3中将环境更改回“开发”,但最后一种方法仍然在“自定义”环境中运行,为什么?以及如何摆脱它?

--- P.S. ---

我还检查过帖子related with environment change here,并尝试在那里使用解决方案(在步骤2中):

#2. change to 'custom' database
ActiveRecord::Base.establish_connection('custom')
Rake::Task['db:create']
Rake::Task['db:migrate']

更改数据库连接而不是更改环境,但db:createdb:migrate仍将在“开发”数据库下运行,但链接的帖子表示应该运行对于“自定义”数据库......很奇怪

---------------重要更新---------------------

我只是意识到第2步中的代码:

#2. change to 'custom' environment 
RAILS_ENV='custom'

Rake::Task['db:create']
Rake::Task['db:migrate']

只有当Rake::Task['db:create']被调用时才会将环境更改为“自定义,如果我注释掉Rake::Task['db:create']行,代码仍会运行在“开发”下:

#2. change to 'custom' environment 
RAILS_ENV='custom'

#Rake::Task['db:create']
#CODE WILL RUN STILL UNDER 'development' environment.

为什么Rake::Task['db:create']会影响我的环境变化......?

2 个答案:

答案 0 :(得分:3)

我意识到这个问题是从一个多月前开始的,但他们说的是什么 - 这是圣诞节

似乎在自己的流程中运行每个rake任务会简化交换环境时的事情吗?

namespace :db do
    task :do_something => :environment do
        unless Rails.env.development? then
           raise "Can only run under development environment, but specified env was #{Rails.env}"
        end 

        #1. run under 'development' environment
        my_helper.run_under_development_env

        #2. do the giggity with custom environment
        command = "bundle exec rake db:create RAILS_ENV=custom"    
        result = %x[#{command}]
        raise "rake task failed..........\n#{result}" if result.include?('rake aborted!')

        command = "bundle exec rake db:migrate RAILS_ENV=custom"    
        result = %x[#{command}]
        raise "rake task failed..........\n#{result}" if result.include?('rake aborted!')


        #3. back to development
        my_helper.run_under_development_env 
    end
end

答案 1 :(得分:1)

仅在耙任务RAILS_ENV ='production'之后键入

以您的情况

rake db:do_something RAILS_ENV ='custom'