Module: MethodizedHash
- Defined in:
- lib/methodize.rb
Class Method Summary
collapse
Instance Method Summary
collapse
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(name, *args) ⇒ Object
41
42
43
44
45
46
47
48
49
50
|
# File 'lib/methodize.rb', line 41
def method_missing(name, *args)
method_name = name.to_s
if method_name[-1,1] == '='
method_name = method_name.chop
key = key?(method_name) ? method_name : method_name.to_sym
self[key] = args[0]
else
__fetch__key__(method_name)
end
end
|
Class Method Details
.extended(base) ⇒ Object
19
20
21
22
23
24
25
26
27
28
29
30
|
# File 'lib/methodize.rb', line 19
def self.extended(base)
@@key_coerce = RUBY_VERSION.match(/^(1\.9[.\d]*|2[.\d]+)$/) ? lambda { |k| k.to_sym } : lambda { |k| k.to_s }
__metaclass__ = base.__metaclass__
base.keys.each do |k|
base.__free_method__(k.to_sym, __metaclass__) if base.public_methods.include?(@@key_coerce.call(k))
end
end
|
Instance Method Details
#[]=(key, value) ⇒ Object
36
37
38
39
|
# File 'lib/methodize.rb', line 36
def []=(key, value)
__free_method__(key) if !keys.include?(key) && public_methods.include?(@@key_coerce.call(key))
super(key,value)
end
|
#__free_method__(sym, __metaclass__ = self.__metaclass__) ⇒ Object
if you have a key that is also a method (such as Array#size) you can use this to free the method and use the method obj.size to access the value of key “size”. you still can access the old method with [method_name]
56
57
58
59
60
61
|
# File 'lib/methodize.rb', line 56
def __free_method__(sym, __metaclass__ = self.__metaclass__)
__sym__ = "__#{sym}__"
__metaclass__.send(:alias_method, __sym__.to_sym, sym) unless respond_to?(__sym__)
__metaclass__.send(:define_method, sym) { __fetch__key__(sym.to_s) }
self
end
|
63
64
65
|
# File 'lib/methodize.rb', line 63
def __metaclass__
class << self; self; end
end
|