Class: Diva::Type::UnionType
Instance Attribute Summary
Attributes inherited from MetaType
Instance Method Summary collapse
- #cast(value) ⇒ Object
- #dump_for_json(value) ⇒ Object
-
#initialize(*types) ⇒ UnionType
constructor
A new instance of UnionType.
- #recommendation_point(v) ⇒ Object
- #recommended_type_of(value) ⇒ Object
- #schema ⇒ Object
- #to_s ⇒ Object
Methods inherited from MetaType
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 |
#recommended_type_of(value) ⇒ Object
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 |
#schema ⇒ Object
265 266 267 |
# File 'lib/diva/type.rb', line 265 def schema @schema ||= { union: @types.map(&:schema) }.freeze end |
#to_s ⇒ Object
261 262 263 |
# File 'lib/diva/type.rb', line 261 def to_s @types.map(&:name).join('|').freeze end |