Class: EasyConfRails
- Inherits:
-
Rails::Railtie
- Object
- Rails::Railtie
- EasyConfRails
- Defined in:
- lib/easyconf-rails.rb
Instance Method Summary collapse
-
#assign_config ⇒ Object
Assign $config to the result of load_config().
-
#hash_to_openstruct(hash) ⇒ Object
Turn a Hash or Array and all of its Hash children into OpenStructs.
-
#load_config ⇒ Object
Load the configuration file at Rails.root/config.yml and the defaults file at Rails.root/config/defaults.yml.
-
#merge_hashes(*hashes) ⇒ Object
Merge two hashes recursively, with precedence going to the earliest Hash with that value defined.
Instance Method Details
#assign_config ⇒ Object
Assign $config to the result of load_config().
100 101 102 103 104 |
# File 'lib/easyconf-rails.rb', line 100 def assign_config() $config = load_config() $config.define_singleton_method(:reload!, &method(:assign_config)) $config end |
#hash_to_openstruct(hash) ⇒ Object
Turn a Hash or Array and all of its Hash children into OpenStructs.
45 46 47 48 49 50 51 52 53 |
# File 'lib/easyconf-rails.rb', line 45 def hash_to_openstruct(hash) (hash.is_a?(Hash) ? hash.keys : (0...hash.length)).each do |key| if hash[key].is_a?(Hash) or hash[key].is_a?(Array) hash[key] = hash_to_openstruct(hash[key]) end end hash.is_a?(Array) ? hash : SemiOpenStruct.new(hash) end |
#load_config ⇒ Object
Load the configuration file at Rails.root/config.yml and the defaults file at Rails.root/config/defaults.yml.
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
# File 'lib/easyconf-rails.rb', line 81 def load_config() config_location = Rails.root + 'config.yml' if File.exists?(config_location) config_hash = YAML.load_file(config_location) else config_hash = {} end defaults_location = Rails.root + 'config' + 'defaults.yml' if File.exists?(defaults_location) defaults_hash = YAML.load_file(defaults_location) else defaults_hash = {} end hash_to_openstruct(merge_hashes(config_hash, defaults_hash)) end |
#merge_hashes(*hashes) ⇒ Object
Merge two hashes recursively, with precedence going to the earliest Hash with that value defined. For example, merge_hashes( {b: 1, c: 2}, {d: 3, c: 4} ) will return {b: 1, d: 3, c: 2}
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
# File 'lib/easyconf-rails.rb', line 60 def merge_hashes(*hashes) merged = {} hashes.each do |hash| hash.each do |key, val| if merged.has_key?(key) and merged[key].is_a?(Hash) and val.is_a?(Hash) merged[key] = merge_hashes(merged[key], val) elsif not merged.has_key?(key) merged[key] = val else # merged[key] and val are not both Hashes, and therefore can't be # merged. merged[key] takes precedence over val, and we do nothing. end end end merged end |