Class: Pandarus::ModelBase

Inherits:
Object
  • Object
show all
Defined in:
lib/pandarus/model_base.rb

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}) ⇒ ModelBase



5
6
7
8
9
10
11
12
13
14
# File 'lib/pandarus/model_base.rb', line 5

def initialize(attributes = {})
  return if attributes.empty?
  attributes.each_pair do |name, value|
    if has_attr? name.to_sym
      assign(name, value)
    else
      raise ArgumentError, "#{name} is not an attribute of #{self.class}"
    end
  end
end

Instance Method Details

#assign(attr_name, value) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
# File 'lib/pandarus/model_base.rb', line 32

def assign(attr_name, value)
  props = attr(attr_name)
  if props[:type]
    if props[:container]
      value = value.map{ |v| props[:type].constantize.new(v) }
    else
      value = props[:type].constantize.new(v)
    end
  end
  instance_variable_set("@#{attr_name}", value)
end

#attr(name) ⇒ Object



16
17
18
# File 'lib/pandarus/model_base.rb', line 16

def attr(name)
  self.class.attribute_map[name.to_sym]
end

#has_attr?(name) ⇒ Boolean



20
21
22
# File 'lib/pandarus/model_base.rb', line 20

def has_attr?(name)
  self.class.attribute_map.has_key? name.to_sym
end

#inspectObject



24
25
26
27
28
29
30
# File 'lib/pandarus/model_base.rb', line 24

def inspect
  Hash[
    self.class.attribute_map.keys.map do |key|
      [key, instance_variable_get("@#{key}")]
    end
  ].inspect.sub(/^\{/,"<#{self.class} ").sub(/\}$/,'>')
end

#to_bodyObject



44
45
46
47
48
49
50
51
52
# File 'lib/pandarus/model_base.rb', line 44

def to_body
  body = {}
  self.class.attribute_map.each_pair do |key, props|
    unless (value = self.send(key).nil?)
      body[props[:external]] = value
    end
  end
  body
end