Class: Wordpress::OpenStruct

Inherits:
Base
  • Object
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 (private)



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/wordpress/ostruct.rb', line 38

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

#[](k) ⇒ Object



24
25
26
# File 'lib/wordpress/ostruct.rb', line 24

def [](k)
  send(k.to_s)
end

#[]=(k, v) ⇒ Object



28
29
30
# File 'lib/wordpress/ostruct.rb', line 28

def []=(k, v)
  send("#{k}=", v)
end

#assign(hash) ⇒ Object



11
12
13
# File 'lib/wordpress/ostruct.rb', line 11

def assign(hash)
  @hash = Hash[hash.map{ |k, v| [k.to_s, v] }]
end

#respond_to_missing?(method_name, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


15
16
17
18
# File 'lib/wordpress/ostruct.rb', line 15

def respond_to_missing?(method_name, include_private = false)
  key = method_name.to_s
  @hash.include?(key) || super
end

#to_hashObject



32
33
34
# File 'lib/wordpress/ostruct.rb', line 32

def to_hash
  @hash
end

#to_sObject



20
21
22
# File 'lib/wordpress/ostruct.rb', line 20

def to_s
  "#<#{self.class.name} #{map { |k, v| "#{k}=#{v}" }.join(" ")}>"
end