module Mixture::Coerce
Handles coercion of objects.
Public Class Methods
Returns a block that takes one argument: the value.
@param from [Mixture::Types::Type]
The type to coerce from.
@param to [Mixture::Types::Type]
The type to coerce to.
@return [Proc{(Object
, Mixture::Types::Object
) => Object}]
# File lib/mixture/coerce.rb, line 49 def self.coerce(from, to) type = from.inheritable.find { |ancestor| coercers.key?(ancestor) } fail CoercionError, "No coercer for #{from}" unless type coercers[type].to(to) end
A hash of the coercers that currently exist. This maps their types to their classes.
@return [Hash{Mixture::Type => Mixture::Coerce::Base}]
# File lib/mixture/coerce.rb, line 38 def self.coercers @_coercers ||= ThreadSafe::Hash.new end
Registers the default coercions.
@return [void]
# File lib/mixture/coerce.rb, line 79 def self.finalize register Array register Boolean register Class register Date register DateTime register Float register Hash register Integer register Nil register Object register Range register Rational register Set register String register Symbol register Time end
Performs the actual coercion, since blocks require a value and type arguments.
@param type [Mixture::Types::Type] The type to coerce to. @param value [Object] The value to coerce. @return [Object] The coerced value.
# File lib/mixture/coerce.rb, line 61 def self.perform(type, value) to = Types.infer(type) from = Types.infer(value) block = coerce(from, to) begin block.call(value, to) rescue CoercionError fail rescue StandardError => e fail CoercionError, "#{e.class}: #{e.message}", e.backtrace end end
Registers a coercion with the module. This uses the {.coercers} constant.
@param coercion [Mixture::Coerce::Base] The coercer to register. @return [void]
# File lib/mixture/coerce.rb, line 30 def self.register(coercion) coercers[coercion.type] = coercion end