Module: DocumentBuilder::Model

Defined in:
lib/document_builder/model.rb

Defined Under Namespace

Modules: ClassMethods

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



79
80
81
82
83
# File 'lib/document_builder/model.rb', line 79

def method_missing(name, *args)
  get_attribute(name)
rescue NoMethodError => e
  raise NoMethodError.new("undefined method '#{name}' for #{self.class}")
end

Class Method Details

.included(base) ⇒ Object



36
37
38
39
40
41
# File 'lib/document_builder/model.rb', line 36

def self.included(base)
  base.extend(ClassMethods)
  base.class_eval do
    include Coercion
  end
end

Instance Method Details

#[](key) ⇒ Object



75
76
77
# File 'lib/document_builder/model.rb', line 75

def [](key)
  get_attribute(key)
end

#add_attribute(name, attribute) ⇒ Object



71
72
73
# File 'lib/document_builder/model.rb', line 71

def add_attribute(name, attribute)
  self.class.add_attribute(name, attribute)
end

#attributesObject



59
60
61
# File 'lib/document_builder/model.rb', line 59

def attributes
  self.class.instance_variable_get(:@attributes)
end

#documentObject



47
48
49
50
51
52
53
# File 'lib/document_builder/model.rb', line 47

def document
  if root && @document.name != root
    @document.at_xpath(root)
  else
    @document
  end
end

#get_attribute(name) ⇒ Object



63
64
65
66
67
68
69
# File 'lib/document_builder/model.rb', line 63

def get_attribute(name)
  if respond_to?(name)
    public_send(name)
  else
    attributes[name].call(document)
  end
end

#initialize(document) ⇒ Object



43
44
45
# File 'lib/document_builder/model.rb', line 43

def initialize(document)
  @document = document
end

#inspectObject



89
90
91
# File 'lib/document_builder/model.rb', line 89

def inspect
  "#<#{self.class}:0x#{self.object_id.to_s(16)}> Attributes: " + JSON.pretty_generate(to_hash)
end

#rootObject



55
56
57
# File 'lib/document_builder/model.rb', line 55

def root
  self.class.instance_variable_get(:@root)
end

#to_hashObject



97
98
99
100
101
102
103
# File 'lib/document_builder/model.rb', line 97

def to_hash
  attributes.inject({}) do |acc, (key, value)|
    obj = get_attribute(key)
    acc[key] = obj.respond_to?(:to_hash) ? obj.to_hash : obj
    acc
  end
end

#to_json(*args) ⇒ Object



93
94
95
# File 'lib/document_builder/model.rb', line 93

def to_json(*args)
  JSON.generate(to_hash)
end

#to_s(*args) ⇒ Object



85
86
87
# File 'lib/document_builder/model.rb', line 85

def to_s(*args)
  JSON.pretty_generate(to_hash)
end