Class: Apiwork::Contract::Object::Coercer

Inherits:
Object
  • Object
show all
Defined in:
lib/apiwork/contract/object/coercer.rb

Constant Summary collapse

PRIMITIVES =
{
  boolean: lambda { |value|
    return value if [true, false].include?(value)
    return true if %w[true 1 yes].include?(value.to_s.downcase)
    return false if %w[false 0 no].include?(value.to_s.downcase)

    nil
  },
  date: lambda { |value|
    return value if value.is_a?(Date)

    Date.parse(value) if value.is_a?(String)
  },
  datetime: lambda { |value|
    return value if value.is_a?(Time) || value.is_a?(DateTime) || value.is_a?(ActiveSupport::TimeWithZone)

    Time.zone.parse(value) if value.is_a?(String)
  },
  decimal: lambda { |value|
    return value if value.is_a?(BigDecimal)

    BigDecimal(value.to_s) if value.is_a?(Numeric) || value.is_a?(String)
  },
  integer: lambda { |value|
    return value if value.is_a?(Integer)

    Integer(value) if value.is_a?(String) && value.match?(/\A-?\d+\z/)
  },
  number: lambda { |value|
    return value if value.is_a?(Float) || value.is_a?(Integer)
    return nil if value.is_a?(String) && value.blank?

    Float(value) if value.is_a?(String)
  },
  string: lambda { |value|
    return value if value.is_a?(String)

    value.to_s
  },
  time: lambda { |value|
    return value if value.is_a?(Time) || value.is_a?(DateTime) || value.is_a?(ActiveSupport::TimeWithZone)

    Time.zone.parse("2000-01-01T#{value}") if value.is_a?(String) && value.match?(/\A\d{2}:\d{2}(:\d{2})?\z/)
  },
  uuid: lambda { |value|
    return value if value.is_a?(String) && value.match?(/\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\z/i)

    nil
  },
}.freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(shape) ⇒ Coercer

Returns a new instance of Coercer.



64
65
66
67
# File 'lib/apiwork/contract/object/coercer.rb', line 64

def initialize(shape)
  @shape = shape
  @type_cache = {}
end

Class Method Details

.coerce(shape, hash) ⇒ Object



59
60
61
# File 'lib/apiwork/contract/object/coercer.rb', line 59

def coerce(shape, hash)
  new(shape).coerce(hash)
end

Instance Method Details

#coerce(hash) ⇒ Object



69
70
71
72
73
74
75
76
77
78
79
# File 'lib/apiwork/contract/object/coercer.rb', line 69

def coerce(hash)
  coerced = hash.dup

  @shape.params.each do |name, param_options|
    next unless coerced.key?(name)

    coerced[name] = coerce_value(coerced[name], param_options)
  end

  coerced
end