class Requisite::ApiModel

Attributes

model[R]

Public Class Methods

new(model={}) click to toggle source
# 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

Public Instance Methods

attribute_from_model(name) click to toggle source
# 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) click to toggle source
# File lib/requisite/api_model.rb, line 18
def convert(name)
  attribute_from_model(name)
end
convert!(name) click to toggle source
# 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) click to toggle source
# 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) click to toggle source
# File lib/requisite/api_model.rb, line 45
def to_json(show_nil: false)
  to_hash(show_nil: show_nil).to_json
end

Private Instance Methods

parse_scalar_hash(name) click to toggle source
# File lib/requisite/api_model.rb, line 62
def parse_scalar_hash(name)
  {}.tap do |result|
    passed_hash = attribute_from_model(name) || {}
    passed_hash.each do |key, value|
      raise BadTypeError.new(value, 'Numeric, String or Boolean') unless (value.kind_of?(Numeric) || value.kind_of?(String) || value.kind_of?(TrueClass) || value.kind_of?(FalseClass))
      result[key] = value
    end
  end
end
parse_typed_array(name, type) click to toggle source
# File lib/requisite/api_model.rb, line 72
def parse_typed_array(name, type)
  [].tap do |result|
    passed_array = attribute_from_model(name) || []
    passed_array.each do |value|
      raise_bad_type_if_type_mismatch(value, type)
      result << value
    end
  end
end
parse_typed_hash(name, hash) click to toggle source
# File lib/requisite/api_model.rb, line 51
def parse_typed_hash(name, hash)
  {}.tap do |result|
    passed_hash = attribute_from_model(name)
    hash.each do |key, value|
      next unless passed_hash && passed_hash[key]
      raise_bad_type_if_type_mismatch(passed_hash[key], value)
      result[key] = passed_hash[key]
    end
  end
end
with_type!(desired_type) { || ... } click to toggle source
# File lib/requisite/api_model.rb, line 82
def with_type!(desired_type)
  yield.tap do |value|
    raise_bad_type_if_type_mismatch(value, desired_type) if value
  end