Class: Requisite::ApiModel

Inherits:
BoundaryObject show all
Defined in:
lib/requisite/api_model.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from BoundaryObject

attribute, attribute!, attribute_keys, attribute_keys_with_inheritance, serialized_attributes

Constructor Details

#initialize(model = {}) ⇒ ApiModel

Returns a new instance of ApiModel.



7
8
9
# File 'lib/requisite/api_model.rb', line 7

def initialize(model={})
  @model = model.kind_of?(Hash) ? Hash[model.map{ |k, v| [k.to_sym, v] }] : model
end

Instance Attribute Details

#modelObject (readonly)

Returns the value of attribute model.



5
6
7
# File 'lib/requisite/api_model.rb', line 5

def model
  @model
end

Instance Method Details

#attribute_from_model(name) ⇒ Object



20
21
22
23
24
25
26
# File 'lib/requisite/api_model.rb', line 20

def attribute_from_model(name)
  if @model.kind_of?(Hash)
    @model[name]
  else
    @model.send(name)
  end
end

#convert(name) ⇒ Object



11
12
13
# File 'lib/requisite/api_model.rb', line 11

def convert(name)
  attribute_from_model(name)
end

#convert!(name) ⇒ Object

Raises:

  • (NotImplementedError)


15
16
17
18
# File 'lib/requisite/api_model.rb', line 15

def convert!(name)
  raise NotImplementedError.new("'#{name}' not found on model") unless model_responds_to_attribute_query?(name)
  attribute_from_model(name)
end

#to_hash(show_nil: false) ⇒ Object



28
29
30
31
32
33
34
35
36
# File 'lib/requisite/api_model.rb', line 28

def to_hash(show_nil: false)
  preprocess_model
  {}.tap do |result|
    self.class.attribute_keys_with_inheritance.each do |meth|
      value = self.send(meth)
      result.merge!({meth => value}) if show_nil || !value.nil?
    end
  end
end

#to_json(show_nil: false) ⇒ Object



38
39
40
# File 'lib/requisite/api_model.rb', line 38

def to_json(show_nil: false)
  to_hash(show_nil: show_nil).to_json
end