Class: Configoro::Hash
- Inherits:
-
HashWithIndifferentAccess
- Object
- HashWithIndifferentAccess
- Configoro::Hash
- Defined in:
- lib/configoro/hash.rb
Instance Method Summary (collapse)
-
- (Configoro::Hash) <<(hsh_or_path)
(also: #push)
Deep-merges additional hash entries into this hash.
-
- (Configoro::Hash) deep_merge!(other_hash)
Recursively merges this hash with another hash.
- - (Object) dup
-
- (Hash) initialize(hsh = {})
constructor
A new instance of Hash.
- - (Object) inspect
-
- (Object) method_missing(meth, *args)
To optimize access, we create a getter method every time we encounter a key that exists in the hash.
Constructor Details
- (Hash) initialize(hsh = {})
A new instance of Hash
7 8 9 10 11 12 13 14 |
# File 'lib/configoro/hash.rb', line 7 def initialize(hsh={}) if hsh.kind_of?(::Hash) then super() update hsh else super end end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
- (Object) method_missing(meth, *args)
To optimize access, we create a getter method every time we encounter a key that exists in the hash. If the key is later deleted, the method will be removed.
75 76 77 78 79 80 81 82 83 84 85 |
# File 'lib/configoro/hash.rb', line 75 def method_missing(meth, *args) if include?(meth.to_s) then if args.empty? then create_getter meth else raise ArgumentError, "wrong number of arguments (#{args.size} for 0)" end else super end end |
Instance Method Details
- (Configoro::Hash) <<(hash) - (Configoro::Hash) <<(path) Also known as: push
Deep-merges additional hash entries into this hash.
28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/configoro/hash.rb', line 28 def <<(hsh_or_path) case hsh_or_path when String raise ArgumentError, "Only files ending in .yml can be added" unless File.extname(hsh_or_path) == '.yml' return self unless File.exist?(hsh_or_path) data = YAML.load_file(hsh_or_path) deep_merge! File.basename(hsh_or_path, ".yml") => data when ::Hash deep_merge! hsh_or_path end end |
- (Configoro::Hash) deep_merge!(other_hash)
Recursively merges this hash with another hash. All nested hashes are forced to be @Configoro::Hash@ instances.
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/configoro/hash.rb', line 53 def deep_merge!(other_hash) other_hash.each_pair do |k, v| tv = self[k] self[k] = if v.kind_of?(::Hash) then if tv.kind_of?(::Hash) then Configoro::Hash.new(tv).deep_merge!(v) else Configoro::Hash.new(v) end else v end end self end |
- (Object) dup
43 44 45 |
# File 'lib/configoro/hash.rb', line 43 def dup Hash.new(self) end |
- (Object) inspect
88 89 90 |
# File 'lib/configoro/hash.rb', line 88 def inspect "#{to_hash.inspect}:#{self.class.to_s}" end |