【问题标题】:Using Rails application config variable in model在模型中使用 Rails 应用程序配置变量
【发布时间】:2012-07-28 06:51:01
【问题描述】:

我在我的 rails 应用程序中定义了自定义配置变量(APP_CONFIG 哈希)。好的,现在我如何在我的模型中使用这些变量?在模型中直接调用 APP_CONFIG['variable'] 是一种非轨道方式!例如,我可以在没有 Rails 环境的情况下使用这些模型。那么APP_CONFIG就没有被定义了。

ATM 我使用模型观察器并为全局配置变量分配实例变量,如下所示:

def after_initialize model
  Mongoid.observers.disable :all do
    model.user_id = APP_CONFIG['user_id'])
    model.variable = User.find(model.user_id).variable
  end
end

但是这个解决方案看起来像猴子补丁。有更好的办法吗?

或者我应该保持最简单,可以在新应用程序(不是 Rails 应用程序)中定义 APP_CONFIG 哈希?

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    我会使用依赖注入。如果你有一个需要各种配置值的对象,你可以通过构造函数注入配置对象:

    class Something
      def initialize(config = APP_CONFIG)
        @config = config
      end
    end
    

    如果配置只需要单个方法,只需将其传递给方法:

    def something(config = APP_CONFIG)
      # do something
    end
    

    Ruby 在调用方法时评估参数。默认值允许您在开发/生产中使用配置对象,而无需手动将其传递给方法并在测试中使用存根而不是实际配置。

    您也可以use the Rails config 代替定义另一个全局变量/常量:

    def something(config = Rails.config)
      # do something
    end
    

    【讨论】:

      【解决方案2】:

      /config/config.yml

      defaults: &defaults
        user_id :100
      
      development:
        <<: *defaults
      
      test:
        <<: *defaults
      
      production:
        <<: *defaults
      

      /config/initializers/app_config.rb

      APP_CONFIG = YAML.load_file("#{Rails.root}/config/config.yml")[Rails.env]
      

      您现在可以在模型中使用APP_CONFIG['user_id']

      【讨论】:

        【解决方案3】:

        使用:before_create 将代码本地化为您的模型:

        class MyModel < ActiveRecord::Base
        
          before_create :set_config
        
          private
        
          def set_config
            self.app_config = APP_CONFIG
          end
        end
        

        或者,作为替代方案,您可以使用ActiveSupport::Concern,这是一种创建模块的非常简洁的方法,您可以在 N 个模型中很好地重用:

        class MyModel < ActiveRecord::Base    
          include AppConfig     
        end
        
        module AppConfig
            extend ActiveSupport::Concern
        
            included do
               #...
            end
        
            module ClassMethods
               #...
            end
        
            def app_config
              APP_CONFIG
            end
        end
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-12-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多