Close and Go BackBack to Viget

Simple Rails/Ruby Application Configuration

Matt Swasey
Matt Swasey, Former Staffer, February 11, 2009

There are a number of plugins and gems that will provide you with various ways to define configuration for your application, search google for "rails configuration plugin". Alternatively, you can use OpenStruct (in Ruby standard library) to create a rich constant with various attributes. Simply create a file called something like app_config.rb in config/initializers and do something like this:

require "ostruct"

App = OpenStruct.new({
  :name => "My App",
  :subtitle => "Hotter than Ebay",
  :admin => OpenStruct.new({
    :username => "admin",
    :password => "secret"
  })
})

So App is created as a constant that you can use anywhere in your application. Each key given to OpenStruct becomes a method on the constant. For example:

class ApplicationController < ActionController::Base

  def authenticated?(username, password)
    username == App.admin.username && 
      password == App.admin.password
  end
end

It's not the most flexible solution, but if you are in need of some quick and easy configuration, it's not a bad option.

blog comments powered by Disqus

We're the Developers

at Viget Labs. We write about web development trends, tips, best practices, industry events, and our projects — all with an emphasis on Ruby on Rails.

Contact Us

Have any questions, comments, ideas, or secrets to share? Let us know.


How many minutes in an hour?

Sorry, you need to have Javascript enabled to use this form. (Don't blame us, blame the spammers!) If you'd like to contact us, please visit our Contact page.