Class: Brapi::Model

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash = {}) ⇒ Model

Returns a new instance of Model.



34
35
36
37
38
39
40
41
42
43
# File 'lib/brapi/model.rb', line 34

def initialize(hash = {})
  hash ||= {}
  hash = hash.transform_keys(&:to_s) if hash.respond_to?(:transform_keys)
  @raw = hash
  self.class.attribute_specs.each do |name, spec|
    value = hash[spec[:json_key]]
    value = hash[name.to_s] if value.nil?
    instance_variable_set("@#{name}", coerce(value, spec[:type]))
  end
end

Instance Attribute Details

#rawObject (readonly)

Returns the value of attribute raw.



65
66
67
# File 'lib/brapi/model.rb', line 65

def raw
  @raw
end

Class Method Details

.attribute(name, type: nil, json_key: nil) ⇒ Object



8
9
10
11
12
# File 'lib/brapi/model.rb', line 8

def attribute(name, type: nil, json_key: nil)
  attr_reader name

  attribute_specs[name] = { type: type, json_key: json_key&.to_s || camelize(name.to_s) }
end

.attribute_specsObject



14
15
16
17
18
19
# File 'lib/brapi/model.rb', line 14

def attribute_specs
  @attribute_specs ||= begin
    parent = superclass.respond_to?(:attribute_specs) ? superclass.attribute_specs : {}
    parent.dup
  end
end

.camelize(snake) ⇒ Object



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

def camelize(snake)
  head, *rest = snake.split("_")
  ([head] + rest.map(&:capitalize)).join
end

.from_h(value) ⇒ Object



21
22
23
24
25
26
# File 'lib/brapi/model.rb', line 21

def from_h(value)
  return nil if value.nil?
  return value if value.is_a?(self)

  new(value)
end

Instance Method Details

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



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

def ==(other)
  other.is_a?(self.class) && other.to_h == to_h
end

#[](name) ⇒ Object



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

def [](name)
  public_send(name) if respond_to?(name)
end

#hashObject



61
62
63
# File 'lib/brapi/model.rb', line 61

def hash
  to_h.hash
end

#to_hObject



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

def to_h
  self.class.attribute_specs.each_with_object({}) do |(name, _), h|
    value = public_send(name)
    h[name] = serialize(value)
  end
end