新手问题 RAILS_ENV 写在命令前后有什么区别呢?

small_fish__ · 2014年02月24日 · 最后由 saiga 回复于 2014年02月24日 · 4386 次阅读

比如 1: 先设置环境:

RAILS_ENV=staging rails c

2: 后设置

rails c RAILS_ENV=staging

第 2 种报错,第一种 ok。 看到 unicorn 执行 rake 也是这样如是写到

run "cd #{deploy_to}/current; /usr/bin/env bundle exec rake RAILS_ENV=#{rails_env} #{ENV['task']}"

他们两者地区别是?

写在前面是环境变量。如果对于非 rails、rake 命令,写在后边,就不能当作环境变量读取。

https://github.com/rails/rails/blob/master/railties/lib/rails/commands/commands_tasks.rb#L5 这里提到某些命令需要参数前置,而 https://github.com/rails/rails/blob/master/railties/lib/rails/commands/commands_tasks.rb#L62 明确表示 console 命令需要在运行之前加载 config/application,参数必需要写在前面。

也就是说运行 rails c 时,首先启动的就是 rails app,而 rails app 需要 RAILS_ENV,所以只能前置。

而后置的是 rake 的写法,运行顺序应该是 rake -> rails app,也就是说 RAILS_ENV 这个变量其实是传递给 rake 再转交到 rails 的。

以上仅供参考,不知道对不对。

理解错误,看4楼

#2 楼 @saiga 原来看源码是一种不错地解决问题方法。。 btw: rails4 可以使用 rails c -e xxx, but rails3  不行, 原来 rails4 才加上的: https://github.com/rails/rails/blob/4-0-stable/railties/lib/rails/commands/console.rb#L18 https://github.com/rails/rails/blob/3-2-stable/railties/lib/rails/commands/console.rb#L20

楼上说的都不对噢~

RAILS_ENV needs to be set before config/application is required

这里的 before 不是参数必须写在前面的意思。

写在前面是 ENV , 写在后面是 ARGV.

rake 写在后面,但是用法和 ENV 一样的原因在这里

def collect_command_line_tasks
  @top_level_tasks = []
  ARGV.each do |arg|
    if arg =~ /^(\w+)=(.*)$/m
      ENV[$1] = $2
    else
      @top_level_tasks << arg unless arg =~ /^-/
    end
  end
  @top_level_tasks.push(default_task_name) if @top_level_tasks.empty?
end

需要 登录 后方可回复, 如果你还没有账号请 注册新账号