Search code examples
ruby-on-railsrubyruby-on-rails-3ruby-on-rails-plugins

Appropriate way to handle settings in Rails3 Plugin?


I'm working on a plugin for Rails3. I'd like to allow users to override some settings. At the moment I'm doing this inside my plugin's Rails::Engine class like:

config.my_setting = :default_value unless config.respond_to? :my_setting

This seems like the wrong way to handle this. Is there a better method or convention most plugins use in Rails3?


Solution

  • I recommend that people create a new settings namespace for their settings in their Railtie:

    module MyPlugin
      class Railtie < Rails::Railtie
        config.my_plugin = ActiveSupport::OrderedHash.new
    
        config.my_plugin.some_default = true
        config.my_plugin.some_other_default = false
    
        initializer "my_plugin.initialize" do |app|
          app.config.my_plugin # the settings, possibly augmented by the user
        end
      end
    end
    

    Then, the user can set your plugin's config or override defaults in their Application class. This is the pattern Rails uses in our internal Railties.

    Like Paul said, you could make it even easier by creating a generator that dumps an initializer with all the possible config settings commented out for their use.