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



76
77
78
79
80
# File 'lib/document_builder/model.rb', line 76

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



33
34
35
36
37
38
# File 'lib/document_builder/model.rb', line 33

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

Instance Method Details

#[](key) ⇒ Object



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

def [](key)
  get_attribute(key)
end

#add_attribute(name, attribute) ⇒ Object



68
69
70
# File 'lib/document_builder/model.rb', line 68

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

#attributesObject



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

def attributes
  self.class.attributes
end

#documentObject



44
45
46
47
48
49
50
# File 'lib/document_builder/model.rb', line 44

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

#get_attribute(name) ⇒ Object



60
61
62
63
64
65
66
# File 'lib/document_builder/model.rb', line 60

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

#initialize(document) ⇒ Object



40
41
42
# File 'lib/document_builder/model.rb', line 40

def initialize(document)
  @document = document
end

#inspectObject



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

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

#rootObject



52
53
54
# File 'lib/document_builder/model.rb', line 52

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

#to_hashObject



94
95
96
97
98
99
100
# File 'lib/document_builder/model.rb', line 94

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



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

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

#to_s(*args) ⇒ Object



82
83
84
# File 'lib/document_builder/model.rb', line 82

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