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
10
11
12
13
14
15
16
# File 'lib/requisite/api_model.rb', line 7

def initialize(model={})
  @model = case model
  when ActionController::Parameters
    Hash[model.to_unsafe_h.map { |k, v| [k.to_sym, v] }]
  when Hash
    Hash[model.map { |k, v| [k.to_sym, v] }]
  else
    model
  end
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



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

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

#convert(name) ⇒ Object



18
19
20
# File 'lib/requisite/api_model.rb', line 18

def convert(name)
  attribute_from_model(name)
end

#convert!(name) ⇒ Object

Raises:

  • (NotImplementedError)


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

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



35
36
37
38
39
40
41
42
43
# File 'lib/requisite/api_model.rb', line 35

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

#to_json(show_nil: false) ⇒ Object



45
46
47
# File 'lib/requisite/api_model.rb', line 45

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