App Settings

Application-wide Settings for Rails

Build Status

Code Climate

Sometimes there is a need to have values stored that can be used anywhere inside a Rails application. Things like the application name, or the company name, etc. are simple use cases. Other times you might want to add oauth key/secret for twitter/facebook.

There are numerous ways in which you can handle that:

  • put it into a initializer
  • create a custom object, maybe subclassing OpenStruct/Struct
  • a Yaml file that you'll load/parse in an initializer file
  • and many other ways

I've been doing a mix of initializers and a custom object, but never been fully happy with those solutions. Rails already has a place for configuration settings for the application, so it made sense to me, to use that.

This tiny gem does just that. Here's how you can do it too:

In your Gemfile, include this gem:

gem 'app_settings'

You can choose to have specific environment settings, but using the config/environments/*.rb files, or put it into the config/application.rb file. Your choice.

inside one of those files:

config.app_settings.appname       = 'My Rails Application'
config.app_settings.company_name  = 'Fancy Pants LLC'

Then, anywhere in your app, you can access those by doing:

Rails.application.config.app_settings.appname       # => 'My Rails Application'
Rails.application.config.app_settings.company_name  # => 'Fancy Pants LLC'

From there, you could put those into the app/controllers/application_controller.rb file and shorten the name and then make it also a helper method. You could also put it into your models as a method or use Rails' config_accessor. You'll get the benefit of having your app settings all in one place.