Class: EasyConfRails
- Inherits:
-
Rails::Railtie
- Object
- Rails::Railtie
- EasyConfRails
- Defined in:
- lib/easyconf-rails.rb
Instance Method Summary collapse
-
#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
#hash_to_openstruct(hash) ⇒ Object
Turn a Hash or Array and all of its Hash children into OpenStructs.
22 23 24 25 26 27 28 29 30 |
# File 'lib/easyconf-rails.rb', line 22 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.
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
# File 'lib/easyconf-rails.rb', line 58 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}
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/easyconf-rails.rb', line 37 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 |