2012-07-30 85 views
5

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

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哈希值?

回答

2

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

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 
0

/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']
0

使用: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 
相关问题