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



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

def method_missing(name, *args)
  attributes.select { |item| item.name == name }.first.call(document)
rescue NoMethodError => e
  raise NoMethodError.new("undefined method '#{name}' for #{self.class}")
end

Class Method Details

.included(base) ⇒ Object



15
16
17
18
19
20
21
22
# File 'lib/document_builder/model.rb', line 15

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

    attr_reader :document
  end
end

Instance Method Details

#[](key) ⇒ Object



32
33
34
# File 'lib/document_builder/model.rb', line 32

def [](key)
  attributes.select { |item| item.name == key.to_sym}.first.call(document)
end

#attributesObject



28
29
30
# File 'lib/document_builder/model.rb', line 28

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

#initialize(document) ⇒ Object



24
25
26
# File 'lib/document_builder/model.rb', line 24

def initialize(document)
  @document = document
end

#inspectObject



46
47
48
# File 'lib/document_builder/model.rb', line 46

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

#to_hashObject



54
55
56
57
58
59
60
# File 'lib/document_builder/model.rb', line 54

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

#to_json(*args) ⇒ Object



50
51
52
# File 'lib/document_builder/model.rb', line 50

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

#to_s(*args) ⇒ Object



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

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