module Reality::Entity::Coercion

Constants

COERCERS

Public Instance Methods

coerce(val, type, **opts) click to toggle source
# File lib/reality/entity/coercion.rb, line 48
def coerce(val, type, **opts)
  if val.kind_of?(Array) && !type.kind_of?(Array)
    val = val.first
  end

  if opts[:parse]
    val = opts[:parse].call(val)
  end

  return nil if val.nil?

  # FIXME: better errors: including field name & class name
  case type
  when Array
    type.count == 1 or fail("Only homogenous array types supported, #{type.inspect} received")
    val.kind_of?(Array) or fail("Array type expected, #{val.inspect} received")
    val.map{|row| coerce(row, type.first, **opts.except(:parse))}.
        derp{|arr| arr.all?{|e| e.is_a?(Entity)} ? List.new(*arr) : arr}
  when Symbol
    parser = COERCERS[type] or fail("No coercion to #{type.inspect}")
    parser.call(val, **opts)
  else
    fail("No parser for type #{type.inspect}")
  end
end
to_simple_type(val) click to toggle source
# File lib/reality/entity/coercion.rb, line 74
def to_simple_type(val)
  case val
  when Rational
    val.to_f
  when nil, Numeric, String, Symbol
    val
  when Array
    val.map{|v| to_simple_type(v)}
  #when Hash
    #val.map{|k, v| [to_simple_type(k), to_simple_type(v)]}.to_h
  when Entity
    val.loaded? ? val.to_h : val.to_s

  when ->(v){v.respond_to?(:to_h)}
    val.to_h
  else
    val.to_s
  end
end