简体   繁体   中英

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?

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.

There are a couple common ways to specify configuration settings in a rails plugin.

I prefer to have an initializer file that contains the plugin settings. This file can be created with the default settings by adding a generator to your plugin. Then the user can run the generator and easily see all the plugin settings in one file.

Checkout the client_side_validations for an example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM