Rails 3 Engine - Provide Config For Users
-
27-09-2019 - |
Question
I can't seem to find any documentation on how to do the following: I need to provide a config variable for any applications using my engine so that they can easily pass settings to my engine.
Does anyone have any links to a proper or accepted way to do this?
EDIT: As an update, I figured out a decent way to do this. Code is below.
# 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
This allows any application using my engine to configure it like below in any of their initializers or their environment.rb file, calling any methods defined in the MyEngine::Configuration
class:
MyEngine.config do |config|
config.some_configuration_option = "Whatever"
end
Solution
Short answer:
Create a file called your_engine_class.rb and put in config/initializers of your hosting app. Here is an example of this file.
module YourEngineClass
class Engine < Rails::Engine
config.param_name = 'value'
end
end
Then inside your main engine.rb you can access:
config.param_name
Longer answer: I created a stub engine that includes this and lots of other standard configuration you'll need, you can use it as a starting point:
http://keithschacht.com/creating-a-rails-3-engine-plugin-gem/
OTHER TIPS
I personally like the pattern Devise uses, which defines a class method in your engine's module and then an initializer in the parent application.
Create a class method to call from the parent application
module YourEngine
class << self
attr_accessor :your_config_var
end
def self.setup(&block)
# You can yield your own object encapsulating your configuration logic/state
yield self
end
end
Call the class method in an initializer in the parent application
YourEngine.setup do |config|
config.your_config_var = "nyan cat"
end
Now you are free to access your_config_var
in your engine's initialization process. You can create a file in your engine's config/initializers
directory or use the Rails Initializer hooks.
I like this approach since you have more control on what configuration object you expose to clients and aren't overriding the engine's config
method.
Seems better to me as follow :
#lib/my_engine.rb
require 'rails'
module MyEngine
class Engine < Rails::Engine
end
def self.config(&block)
yield Engine.config if block
Engine.config
end
end