Your friends at Viget present Extend, a Code & Technology Blog

Simple Rails/Ruby Application Configuration

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.


Get More From Viget

Subscribe to get our monthly newsletter and occasional special announcements.