Module: Methodize
- 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
23
24
25
26
27
28
29
30
31
32
33
|
# File 'lib/methodize.rb', line 23
def method_missing(name, *args)
method_name = name.to_s
if method_name[-1,1] == '='
method_name = method_name.chop
self.key?(method_name) ? key = method_name : key = method_name.to_sym
self[key] = args[0]
else
self.key?(method_name) ? key = method_name : key = method_name.to_sym
self[key]
end
end
|
Class Method Details
.extended(base) ⇒ Object
2
3
4
5
6
7
8
9
10
11
12
|
# File 'lib/methodize.rb', line 2
def self.extended(base)
@@key_coerce = RUBY_VERSION.start_with?("1.9") ? lambda { |k| k.to_sym } : lambda { |k| k.to_s }
base.keys.each do |k|
base.__free_method__(k.to_sym) if base.public_methods.include?(@@key_coerce.call(k))
end
end
|
Instance Method Details
#[](key) ⇒ Object
14
15
16
|
# File 'lib/methodize.rb', line 14
def [](key)
__normalize__(super(key))
end
|
#[]=(key, value) ⇒ Object
18
19
20
21
|
# File 'lib/methodize.rb', line 18
def []=(key, value)
__free_method__(key) if !self.keys.include?(key) && self.public_methods.include?(@@key_coerce.call(key))
super(key,value)
end
|
#__free_method__(sym) ⇒ 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]
39
40
41
42
43
|
# File 'lib/methodize.rb', line 39
def __free_method__(sym)
self.__metaclass__.send(:alias_method, "__#{sym.to_s}__".to_sym, sym) unless self.respond_to?("__#{sym.to_s}__")
self.__metaclass__.send(:define_method, sym) { method_missing(sym.to_s) }
self
end
|
45
46
47
|
# File 'lib/methodize.rb', line 45
def __metaclass__
class << self; self; end
end
|