Class: Wordpress::OpenStruct

Inherits:
Base
  • Object
show all
Defined in:
lib/wordpress/ostruct.rb

Direct Known Subclasses

Configuration

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)



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

def method_missing(method_name, *args, &block)
  key = method_name.to_s
  key = key[-1] == '=' ? key[0...-1] : key
  if @hash.include?(key)
    define_accessor(key)
    send(method_name, *args, &block)
  else
    super
  end
end

Instance Method Details

#[](k) ⇒ Object



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

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

#[]=(k, v) ⇒ Object



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

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

Returns:

  • (Boolean)


16
17
18
19
20
21
22
23
# File 'lib/wordpress/ostruct.rb', line 16

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

#to_hashObject



37
38
39
# File 'lib/wordpress/ostruct.rb', line 37

def to_hash
  @hash
end

#to_sObject



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

def to_s
  "#<#{self.class.name} #{@hash.keys.map{ |k| "#{k}=#{send(k).to_s}" }.join(" ")}>"
end