0

I have an older application running Ruby on Rails 2.2, and I'm having trouble getting a gem to work because it can't find the current environment with Rails.env:

$ script/console
>> Rails.env
NoMethodError: undefined method `env' for Rails:Module
from (irb):1

The gem is set up to use Rails.env when Rails is defined, and RAILS_ENV when it's not. But I seem to have a Rails object without an env method (even though I read that method was added in Rails 2). Any idea what's going on?

2
  • I don't have 2.2 installed (2.3.8 has that method), but you can look @ what methods are available by running this in the console: puts Rails.methods.sort. Commented Dec 10, 2010 at 17:58
  • There are 138 methods listed, but no env. Commented Dec 10, 2010 at 19:08

2 Answers 2

4

Rails.env was introduced in Rails 2.3. You probably want to upgrade to Rails 2.3 if possible.

Otherwise, try this in a config/initializers/rails_env.rb:

require 'active_support/string_inquirer'
def Rails.env
  @_env ||= ActiveSupport::StringInquirer.new(ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development")
end
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! But no ActiveSupport::StringInquirer on my system. I suppose I could make it a straight string?
You can try that, depends on the gem you are using. If it does Rails.env.production? then you need the StringInquirer. In that case, you can backport it: github.com/rails/rails/blob/master/activesupport/lib/…
2

The Rails module has always been in rails. It is not new in 3, so checking to see if it's defined is the wrong way to go about things. The correct way to determine if you can use Rails.env is to do Rails.respond_to? :env.

4 Comments

Thanks! I'll pass that along to the gem maintainer. In the meantime, what makes most sense as a workaround? Is there any harm in defining Rails.env to be RAILS_ENV?
@jrdioko For 2.x compatability you could do that, but it's not a good idea to always just use RAILS_ENV as it is deprecated in 3.
Rails.method_defined?(:env) returns false even on Rails 3.
I think it should be Rails.respond_to?(:env).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.