Class: TinyDyno::Adapter::AttributeValue::Marshaler

Inherits:
Object
  • Object
show all
Defined in:
lib/tiny_dyno/adapter/attributes.rb

Instance Method Summary collapse

Instance Method Details

#format(type: 'auto', obj:) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/tiny_dyno/adapter/attributes.rb', line 32

def format(type: 'auto', obj:)
  return { null: true } if obj.nil?
  type = obj.class.to_s if type == 'auto'
  case type.to_s
    when 'Hash'
      obj.each.with_object(m:{}) do |(key, value), map|
        map[:m][key.to_s] = format(type: value.class, obj: value)
      end
    when 'Array'
      obj.each.with_object(l:[]) do |value, list|
        list[:l] << format(type: value.class, obj: value)
      end
    when 'String' then { s: obj }
    when 'Symbol' then { s: obj.to_s }
    when 'Numeric', 'Fixnum', 'Float', 'Integer', 'BigDecimal' then numeric_format(type.to_s,obj)
    when 'StringIO', 'IO' then { b: obj }
    when 'Set' then format_set(obj)
    when 'TrueClass', 'FalseClass', 'TinyDyno::Boolean'
      # ToDo, how can we initialize a boolean field into a valid state?
      raise TinyDyno::Errors::InvalidValueType.new(klass: self.class, name: type, value: obj) unless [true,false,nil].include?(obj)
      { bool: obj }
    when 'NilClass' then { null: true }
  else
    msg = "unsupported type, expected Hash, Array, Set, String, Numeric, "
    msg << "IO, true, false, or nil, got #{obj.class.name}"
    raise ArgumentError, msg
  end
end