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.



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

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

Instance Method Details

#cast(value) ⇒ Object



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

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

#dump_for_json(value) ⇒ Object



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

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

#recommendation_point(v) ⇒ Object



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

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


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

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

#schemaObject



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

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

#to_sObject



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

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