Class: Wordpress::OpenStruct
- Inherits:
-
Base
- Object
- Base
- Wordpress::OpenStruct
show all
- Defined in:
- lib/wordpress/ostruct.rb
Instance Method Summary
collapse
Methods inherited from Base
#metaclass
Constructor Details
#initialize(hash = {}) ⇒ OpenStruct
Returns a new instance of OpenStruct.
7
8
9
|
# File 'lib/wordpress/ostruct.rb', line 7
def initialize(hash = {})
assign(hash)
end
|
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method_name, *args, &block) ⇒ Object
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
# File 'lib/wordpress/ostruct.rb', line 39
def method_missing(method_name, *args, &block)
key = method_name.to_s
key = key[-1] == '=' ? key[0...-1] : key
if @hash.include?(key)
metaclass.send(:define_method, key, Proc.new{
v = @hash[key]
v.is_a?(Hash) ? Wordpress::OpenStruct.new(v) : v
})
metaclass.send(:define_method, "#{key}=", Proc.new{ |v|
@hash[key] = v
})
return send(method_name, *args, &block)
end
super
end
|
Instance Method Details
25
26
27
|
# File 'lib/wordpress/ostruct.rb', line 25
def [](k)
send(k.to_s)
end
|
#[]=(k, v) ⇒ Object
29
30
31
|
# File 'lib/wordpress/ostruct.rb', line 29
def []=(k, v)
send("#{k}=", v)
end
|
#assign(hash = {}) ⇒ Object
11
12
13
14
|
# File 'lib/wordpress/ostruct.rb', line 11
def assign(hash = {})
@hash = Hash[hash.map{ |k, v| [k.to_s, v] }]
self
end
|
#respond_to_missing?(method_name, include_private = false) ⇒ Boolean
16
17
18
19
|
# File 'lib/wordpress/ostruct.rb', line 16
def respond_to_missing?(method_name, include_private = false)
key = method_name.to_s
@hash.include?(key) || super
end
|
33
34
35
|
# File 'lib/wordpress/ostruct.rb', line 33
def to_hash
@hash
end
|
21
22
23
|
# File 'lib/wordpress/ostruct.rb', line 21
def to_s
"#<#{self.class.name} #{map { |k, v| "#{k}=#{v}" }.join(" ")}>"
end
|