Search code examples
ruby-on-railsrails-engines

Rails mountable engine: how should apps set configuration variables?


I have a mountable engine called Blog that apps can use.

What's the best way to allow apps that use the engine to set a configuration variable like site_name (so that the engine can display it in the design)?

Update:

I've seen some gems create a 'config/initializers/gem_name.rb' file. Is there any specification on how to:

  1. Create a file like that on the engine's side
  2. Copy it into the app's side
  3. How to access those set variables on the engine's side?

I tried creating Blog.site_name = "My Site" in the app's config/initializers/blog.rb file but get an Undefined method error.


Solution

  • Figured out an even better solution that also allows you to set default values (incase the app using the engine doesn't specify a config)...

    1. Create config variables in your app's /config/initializers/blog.rb like this:
        Blog.setup do |config|
            config.site_name = "My Site Name"
        end
    
    1. In your engine's /lib/blog/engine.rb set default values like this:
        module Blog
        
             self.mattr_accessor :site_name
             self.site_name = "Site Name"
             # add default values of more config vars here
        
             # this function maps the vars from your app into your engine
             def self.setup(&block)
                yield self
             end
        
        end
    
    1. Now you can simply access the config variables in your engine like this:

    Blog.site_name

    Much cleaner.