Class: OpenHash
- Inherits:
-
Object
- Object
- OpenHash
- Defined in:
- lib/ohash.rb
Overview
Since I personally hate OpenStructs, this is a Hash with the same features, but it’s mergeable etc…
Inspired by Mash: www.intridea.com/2008/4/12/mash-mocking-hash-for-total-poser-objects?blog=company
o = OpenHash.new
-
Access to hash methods
o._merge!(=> 12, :bar => 22) o._keys #=> [:foo, :bar]
-
Member access
o.foo == 12 #=> true o.foo = 33 o == 12 #=> false
-
Membership test
o.foo? #=> true o.bar? #=> true o.bla? #=> false
-
Quick population with sub hashes
o.bla!.goo = 23 o.bla!.yadda!.rofl = 42 o.bla? #=> true o.bla?.goo? #=> true
Class Method Summary collapse
Instance Method Summary collapse
-
#as_hash ⇒ Object
Returns this OpenHash as a simple hash.
-
#initialize(*args) ⇒ OpenHash
constructor
Same as for Hash.
- #inspect ⇒ Object
- #to_hash ⇒ Object (also: #to_h)
- #to_s ⇒ Object
Constructor Details
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(meth, *args, &block) ⇒ Object (protected)
Emulates […], …=, …!, …?, _… and direct member access methods.
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 |
# File 'lib/ohash.rb', line 84 def method_missing( meth, *args, &block ) method = meth.to_s case method when *%w{[] []=} @hash.send(meth, *args, &block) when %r{^_} ret = @hash.send(method[1..-1], *args, &block) if ret.respond_to?(:to_ohash) and meth != :_default ret.to_ohash else ret end when %r{.=$} super unless args.length == 1 @hash[method[0...-1].to_sym] = args.first when %r{.!$} super unless args.empty? @hash[method[0...-1].to_sym] ||= OpenHash.new when %r{.\?$} super unless args.empty? @hash.keys.include?(method[0...-1].to_sym) else @hash[meth] end end |
Class Method Details
Instance Method Details
#as_hash ⇒ Object
Returns this OpenHash as a simple hash. Modifying the returned hash will modify the original OpenHash as well.
66 67 68 |
# File 'lib/ohash.rb', line 66 def as_hash @hash end |
#inspect ⇒ Object
74 75 76 |
# File 'lib/ohash.rb', line 74 def inspect @hash.inspect end |
#to_hash ⇒ Object Also known as: to_h
55 56 57 |
# File 'lib/ohash.rb', line 55 def to_hash @hash.dup end |
#to_s ⇒ Object
70 71 72 |
# File 'lib/ohash.rb', line 70 def to_s @hash.to_s end |