Class: EnotasApi::TypeHandler

Inherits:
Object
  • Object
show all
Defined in:
lib/enotas_api/support/type_handler.rb

Constant Summary collapse

VALIDATOR =
{
  boolean: ->(value, _type) { value.is_a?(TrueClass) || value.is_a?(FalseClass) },
  decimal: ->(value, _type) { value.is_a?(Float) || value.is_a?(Integer) || value.is_a?(BigDecimal) },
  integer: ->(value, _type) { value.is_a?(Integer) },
  string: ->(value, _type) { value.is_a?(String) },
  datetime: ->(value, _type) { value.is_a?(DateTime) || value.is_a?(Date) },
  array: ->(value, _type) { value.is_a?(Array) },
  entity: ->(value, type) { value.is_a?(type) || value.is_a?(Hash) }
}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(type) ⇒ TypeHandler

Returns a new instance of TypeHandler.

Raises:



18
19
20
21
22
23
# File 'lib/enotas_api/support/type_handler.rb', line 18

def initialize(type)
  @type = type
  @validator_type = type.is_a?(Class) && type < EnotasApi::Entity ? :entity : type
  @validator = VALIDATOR[@validator_type]
  raise EnotasApi::Error, "Type #{type} not supported" unless @validator
end

Instance Method Details

#entity?Boolean

Returns:

  • (Boolean)


25
26
27
# File 'lib/enotas_api/support/type_handler.rb', line 25

def entity?
  @validator_type == :entity
end

#validate!(value) ⇒ Object

Raises:



29
30
31
32
33
# File 'lib/enotas_api/support/type_handler.rb', line 29

def validate!(value)
  return if value.nil? || @validator.call(value, @type)

  raise EnotasApi::Error, "Invalid value set '#{value}:#{value.class}' for type '#{@type}'"
end