Skip to content

Instantly share code, notes, and snippets.

@dv
Created August 15, 2014 13:06
Show Gist options
  • Save dv/23622b126ea02d12da97 to your computer and use it in GitHub Desktop.
Save dv/23622b126ea02d12da97 to your computer and use it in GitHub Desktop.
Easy Settings in Rails
# lib/deep_struct.rb
# Source: http://andreapavoni.com/blog/2013/4/create-recursive-openstruct-from-a-ruby-hash
require 'ostruct'
module Utils
class DeepStruct < OpenStruct
def initialize(hash=nil)
@table = {}
@hash_table = {}
if hash
hash.each do |k,v|
@table[k.to_sym] = (v.is_a?(Hash) ? self.class.new(v) : v)
@hash_table[k.to_sym] = v
new_ostruct_member(k)
end
end
end
def to_h
@hash_table
end
end
end
# config/initializers/settings.rb
settings = YAML::load_file(Rails.root.join("config", "settings.yml"))
settings.merge(settings[Rails.env] || {})
::Settings = Utils::DeepStruct.new(settings)
# config/settings.yml
aws_key: lfjdsklafjdklsafjdsa
aws_secret_key: jkfldsjafldsafjdsa
timeout: 5
production:
aws_key: fdkslafjkdlsaf
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment