Class: Lego::Model

Inherits:
Object
  • Object
show all
Defined in:
lib/lego/model.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attrs = {}) ⇒ Model

Returns a new instance of Model.



18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/lego/model.rb', line 18

def initialize(attrs={})
  @attributes = {}.tap do |h|
    self.class.parsers.each do |name, parser|
      value = attrs.delete(name)
      begin
        h[name] = parser.coerce(value)
      rescue Lego::CoerceError => e
        fail ArgumentError, ":#{name} => #{e.message}"
      end
    end
  end.freeze
  fail ArgumentError, "Unknown attributes: #{attrs}" unless attrs.empty?
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &block) ⇒ Object



34
35
36
# File 'lib/lego/model.rb', line 34

def method_missing(name, *args, &block)
  attributes.fetch(name.to_sym) { super }
end

Instance Attribute Details

#attributesObject (readonly)

Returns the value of attribute attributes.



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

def attributes
  @attributes
end

Class Method Details

.attribute(attr, type, *args) ⇒ Object



5
6
7
# File 'lib/lego/model.rb', line 5

def attribute(attr, type, *args)
  parsers[attr.to_sym] = Lego.value_parser(type, *args)
end

.attribute_namesObject



13
14
15
# File 'lib/lego/model.rb', line 13

def attribute_names
  parsers.keys
end

.coerce(hash) ⇒ Object



38
39
40
# File 'lib/lego/model.rb', line 38

def self.coerce(hash)
  hash.instance_of?(self) ? hash : self.new(hash)
end

.parse(hash) ⇒ Object



42
43
44
45
46
# File 'lib/lego/model.rb', line 42

def self.parse(hash)
  Lego.just(self.coerce(hash))
rescue Lego::CoerceError => e
  Lego.fail(e.message)
end

.parsersObject



9
10
11
# File 'lib/lego/model.rb', line 9

def parsers
  @_parsers ||= {}
end

Instance Method Details

#==(o) ⇒ Object Also known as: eql?

Equality



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

def ==(o)
  o.class == self.class && o.attributes == attributes
end

#as_jsonObject

Serialize



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

def as_json
  {}.tap do |h|
    attributes.each do |attr, val|
      h[attr] = val.as_json
    end
  end
end

#hashObject



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

def hash
  attributes.hash
end