ostruct snippets

A simple configuration framework for storing a Rails app's configuration in YAML

Tagged yaml, rails, configuration, ostruct  Languages ruby

Create config/initializers/configuration.rb:

require 'ostruct'

# From https://www.ruby-forum.com/topic/137104
class NestedOstruct
   def self.new(hash)
     OpenStruct.new(hash.inject({}){|r,p| r[p[0]] = p[1].kind_of?(Hash) ?  NestedOstruct.new(p[1]) : p[1]; r })
   end
end

config = YAML.load_file(Rails.root.join('config', 'application.yml'))[Rails.env].symbolize_keys
AppConfig = NestedOstruct.new(config)

Create config/application.yml:

development:
  twitter:
    api_key: xxx
    api_secret: xxx
production:
...

Use it in your application:

AppConfig.twitter.api_key