Class: OpenHash

Inherits:
Object
  • Object
show all
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

Constructor Details

#initialize(*args) ⇒ OpenHash

Same as for Hash.



51
52
53
# File 'lib/ohash.rb', line 51

def initialize( *args )
    @hash = Hash.new(*args)
end

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

.[](*args) ⇒ Object



40
41
42
43
44
# File 'lib/ohash.rb', line 40

def []( *args )
    o = OpenHash.new
    o.instance_variable_set(:@hash, Hash[*args])
    o
end

Instance Method Details

#as_hashObject

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

#inspectObject



74
75
76
# File 'lib/ohash.rb', line 74

def inspect
    @hash.inspect
end

#to_hashObject Also known as: to_h



55
56
57
# File 'lib/ohash.rb', line 55

def to_hash
    @hash.dup
end

#to_sObject



70
71
72
# File 'lib/ohash.rb', line 70

def to_s
    @hash.to_s
end