I'm developing a Rails Engine that handles the OAuth mechanism with a third party. I would like to have all the configuration in a Struct attribute, so all the engine config data is stored together:
require 'rails'
module ThirdParty
class Engine < ::Rails::Engine
initializer "third-party.some_init_task" do |app|
ThirdPartyConfig = Struct.new(:uri, :client_id, :client_secret, :redirect_uri)
app.config.thirdparty = ThirdPartyConfig.new
app.config.thirdparty.uri = "https://thirdparty.com"
app.config.thirdparty.client_id = ""
app.config.thirdparty.client_secret = ""
app.config.thirdparty.redirect_uri = ""
end
end
end
Some of the configuration should be defined in the application level initializers:
class Application < Rails::Application
config.thirdparty.client_id = <valid_client_id>
config.thirdparty.client_secret = <valid_client_secret>
config.thirdparty.redirect_uri = <redirect_uri>
end
But as config.thirdparty still is undefined while loading the application initializer, it fails.
1 What are Engines? Engines can be considered miniature applications that provide functionality to their host applications. A Rails application is actually just a "supercharged" engine, with the Rails::Application class inheriting a lot of its behavior from Rails::Engine .
The well-known devise gem , for example, is based on Rails engines. But what is it exactly? Well, simply put a Rails engine is the miniature edition of a Rails application. It comes with an app folder, including controllers, models, views, routes, migrations...
Rails::Railtie is the core of the Rails framework and provides several hooks to extend Rails and/or modify the initialization process. Every major component of Rails (Action Mailer, Action Controller, Active Record, etc.) implements a railtie. Each of them is responsible for their own initialization.
Try specifying the load order for the initializer in your engine. You should be able to force it to load before the application configuration runs. Here is a guess at the point you want to load your initializer
initializer "third-party.some_init_task", :before=> :load_config_initializers do |app|
If that does not work, try loading it before another initializer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With