application.rb中未定义的方法'env'

时间:2013-11-28 16:05:58

标签: ruby-on-rails ruby railstutorial.org

我在Michael Hartl的书中学习Ruby on Rails。我试图添加动态生成一个秘密令牌。

secret_token.rb:

require 'securerandom'

def secure_token
  token_file = Rails.root.join('.secret')
  if File.exist?(token_file)
    # Use the existing token.
    File.read(token_file).chomp
  else
    # Generate a new token and store it in token_file.
    token = SecureRandom.hex(64)
    File.write(token_file, token)
    token
  end
end

Blog::Application.config.secret_key_base = secure_token

application.rb文件:

require File.expand_path('../boot', __FILE__)

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env) if defined?(Bundler)

module Blog
  class Application < Rails::Application
  end
end

但是在执行操作期间出错:

yaroslav@yaroslavpc:~/rails/blog$ rails generate rspec:install
/home/yaroslav/rails/blog/config/application.rb:7:in `<top (required)>': undefined method `env' for Rails:Module (NoMethodError)
    from /home/yaroslav/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/commands.rb:44:in `require'
    from /home/yaroslav/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/commands.rb:44:in `<top (required)>'
    from bin/rails:4:in `require'
    from bin/rails:4:in `<main>'

ROR和Ruby版本:

yaroslav@yaroslavpc:~/rails/blog$ rails --version
Rails 4.0.0
yaroslav@yaroslavpc:~/rails/blog$ ruby -v
ruby 2.0.0p247 (2013-06-27 revision 41674) [i686-linux]

一点点帮助会非常酷。

1 个答案:

答案 0 :(得分:1)

您正在使用Rails 4.0,我认为Rails.env适用于3.0。

试试这个:

if Rails.respond_to? :env
    Bundler.require(:default, Rails.env) if defined?(Bundler)
else
    Bundler.require(:default, RAILS_ENV) if defined?(Bundler)
end