我似乎找不到关于如何执行以下操作的任何文档:我需要为使用我的引擎的任何应用程序提供一个配置变量,以便他们可以轻松地将设置传递给我的引擎。
有没有人有任何正确或可接受的方式来做到这一点?
编辑:作为更新,我想出了一个体面的方法来做到这一点。代码如下。
# file: lib/my_engine.rb
module MyEngine
class Engine < Rails::Engine
initializer "my_engine.configure_rails_initialization" do |app|
# Engine configures Rails app here, this is not what my question was about
end
end
# This is what I was trying to figure out
def self.config(&block)
@@config ||= MyEngine::Configuration.new
yield @@config if block
return @@config
end
end
这允许任何使用我的引擎的应用程序在它们的任何初始化程序或它们的 environment.rb 文件中像下面这样配置它,调用在
MyEngine::Configuration
中定义的任何方法。类(class):MyEngine.config do |config|
config.some_configuration_option = "Whatever"
end
最佳答案
简短的回答:
创建一个名为 your_engine_class.rb 的文件并放入托管应用程序的配置/初始化程序。这是此文件的示例。
module YourEngineClass
class Engine < Rails::Engine
config.param_name = 'value'
end
end
然后在你的 main engine.rb 你可以访问:
config.param_name
更长的答案:我创建了一个 stub 引擎,其中包含此引擎以及您需要的许多其他标准配置,您可以将其用作起点:
http://keithschacht.com/creating-a-rails-3-engine-plugin-gem/
关于ruby-on-rails-3 - Rails 3 引擎 - 为用户提供配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4065699/