【问题标题】:Undefined method 'env' in application.rb [closed]application.rb 中未定义的方法“env”[关闭]
【发布时间】:2013-11-28 16:05:57
【问题描述】:

我在 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]

一点帮助会很酷。

【问题讨论】:

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


    【解决方案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
    

    【讨论】:

    • 非常感谢。在require 'rails / all' 的顶部添加字符串时效果很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多