ENV directly accesses the environment of the current process. If you
do the set command in Bash you'll see the same variables as you do in
script/console when you run "puts ENV.inspect". So ENV["RAILS_ENV"]
is a shell variable that can get set on the command line. RAILS_ENV
itself is a Ruby constant. It should be set exactly once in any run.
However there are many places in the Rails code where this gets
reset... especially in the testing code. The thinking here is that
its better to be safe (not destroy your production db for example)
than "proper". Its worth noting the the Merb equivalent Merb.env uses
a class variable which can be set from the ENV["MERB_ENV"] shell
variable, which is syntactically more proper. So, why do we see both
littered through the code? Well unless the whole Rails stack is
initialized, RAILS_ENV may not be set. Some programmers just set it
themselves and deal with the warning in things like script/runner
tasks others just get in the habit of using ENV["RAILS_ENV"]
everywhere (even places like controllers where it should not be used).
More specific answers below
On Tue, Dec 23, 2008 at 19:55, lowellv <
lvi...@gmail.com> wrote:
>
> Maybe this can be of some help..
>
>
http://wiki.rubyonrails.org/rails/pages/Environments
>
> On Dec 22, 12:21 pm, Glenn Little <
lit...@cs.ucsd.edu> wrote:
>> I'm confused about the difference and relationship between
>> the RAILS_ENV constant, and ENV['RAILS_ENV']. What is the
>> intent in usage between the two?
>>
>> My initial thought was that ENV['RAILS_ENV'] was sort of the
>> outside world's way of communicating with the rails app, but
>> maybe that rails would set RAILS_ENV from that early and then
>> just go from there.
>>
This is how things are supposed to work
>> But I find plugins and bits of code here and there that use
>> ENV['RAILS_ENV'] in decision logic directly, in addition to code
>> that uses RAILS_ENV in decision logic.
>>
This is just bad code... it happens ;-) I think some devs do this
because they test their plugins outside the Rails enviroment, but they
should probably just be setting RAILS_ENV in their spec_helper or
test_helper
>> Is there a "more correct" way? And when exactly does RAILS_ENV
>> get set?
>>
During the configuration step. I believe its during the processing of
boot.rb... but its been moved a few times so I'm not sure.
>> Lastly, in a shell with no RAILS_ENV set, I do:
>>
>> % echo $RAILS_ENV
>> RAILS_ENV: Undefined variable.
>>
>> % script/console production
>> >> RAILS_ENV
>> => "production"
>> >> ENV['RAILS_ENV']
>> => "development"
>>
>> Huh? Where is that "development" coming from?
>>
I'd say that is a bug. ENV['RAILS_ENV'] should be nil in the case.
However it would not supprise me to see something like
ENV['RAILS_ENV'] ||= 'development' somewhere in Railties.
>> Pointers to decent documentation on this stuff very much welcomed!
>>
>> Thanks...
>>
>> -glenn
> >
>
Best,
Rob