我在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哈希?
答案 0 :(得分: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
答案 1 :(得分: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']
答案 2 :(得分: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