Class: Diva::Type::UnionType

Inherits:
MetaType show all
Defined in:
lib/diva/type.rb

Instance Attribute Summary

Attributes inherited from MetaType

#name

Instance Method Summary collapse

Methods inherited from MetaType

#inspect

Constructor Details

#initialize(*types) ⇒ UnionType

Returns a new instance of UnionType.



245
246
247
248
# File 'lib/diva/type.rb', line 245

def initialize(*types)
  @types = types.flatten.map(&Diva.method(:Type)).freeze
  super("union_#{@types.map(&:name).join('_')}")
end

Instance Method Details

#cast(value) ⇒ Object



254
255
256
# File 'lib/diva/type.rb', line 254

def cast(value)
  recommended_type_of(value).cast(value)
end

#dump_for_json(value) ⇒ Object



258
259
260
# File 'lib/diva/type.rb', line 258

def dump_for_json(value)
  recommended_type_of(value).dump_for_json(value)
end

#recommendation_point(value) ⇒ Object



250
251
252
# File 'lib/diva/type.rb', line 250

def recommendation_point(value)
  @types.map { |t| t.recommendation_point(value) }.compact.min
end


270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
# File 'lib/diva/type.rb', line 270

def recommended_type_of(value)
  available_types = @types.map { |t|
    [t, t.recommendation_point(value)]
  }.select { |_, p| p }
  unless available_types.empty?
    best, = available_types.min_by { |_, p| p }
    return best
  end
  @types.each do |type|
    type.cast(value)
    return type
  rescue Diva::InvalidTypeError
    # try next
  end
  raise Diva::InvalidTypeError, "The value is not #{self}"
end

#schemaObject



266
267
268
# File 'lib/diva/type.rb', line 266

def schema
  @schema ||= { union: @types.map(&:schema) }.freeze
end

#to_sObject



262
263
264
# File 'lib/diva/type.rb', line 262

def to_s
  @types.map(&:name).join('|').freeze
end