【问题标题】:Where to Put Global Constant in Rails 3Rails 3 中全局常量的放置位置
【发布时间】:2011-12-07 19:00:43
【问题描述】:

我想在 Rails 3 中定义全局常量,但在 Google 上看到这么多不同的答案让我很困惑。

我正在尝试this solution,但它不起作用并出现错误:

Undefined method `music_type' for #<Rails::Application::Configuration:0xb7ac0230>

在/config/application.rb中

module RailsRoot
 Class Application < Rails :: Application
 config.music_type = '2'
 end
end

在控制器中

RailsRoot::Application::config.music_type

不知道我做错了什么。

谢谢

【问题讨论】:

  • 它工作...我忘了重启服务器

标签: ruby-on-rails ruby-on-rails-3 initialization


【解决方案1】:

你需要一个专门的 gem,比如 http://rubygems.org/gems/rails-3-settings

this线程有详细解答

【讨论】:

    【解决方案2】:

    我认为,最好的方法是在 config/initializers/ 文件夹中定义自己的初始化程序。

    例子:

    config/initializers/文件夹中创建my_initializer.rb,内容如下:

    require 'socket'
    
    def local_ip
      orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off      reverse DNS resolution temporarily
    
      UDPSocket.open do |s|
        s.connect '64.233.187.99', 1
        s.addr.last
      end
    ensure
      Socket.do_not_reverse_lookup = orig
    end
    
    SERVER_IP = local_ip
    

    并且在某些控制器中使用该常量:

    log_it "Server IP address is: #{SERVER_IP}"
    

    【讨论】:

      猜你喜欢
      • 2011-09-09
      • 1970-01-01
      • 2013-10-26
      • 1970-01-01
      • 2012-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多