Module: Mixture::Coerce

Defined in:
lib/mixture/coerce.rb,
lib/mixture/coerce/nil.rb,
lib/mixture/coerce/set.rb,
lib/mixture/coerce/base.rb,
lib/mixture/coerce/date.rb,
lib/mixture/coerce/hash.rb,
lib/mixture/coerce/time.rb,
lib/mixture/coerce/array.rb,
lib/mixture/coerce/class.rb,
lib/mixture/coerce/float.rb,
lib/mixture/coerce/range.rb,
lib/mixture/coerce/object.rb,
lib/mixture/coerce/string.rb,
lib/mixture/coerce/symbol.rb,
lib/mixture/coerce/boolean.rb,
lib/mixture/coerce/integer.rb,
lib/mixture/coerce/datetime.rb,
lib/mixture/coerce/rational.rb

Overview

Handles coercion of objects.

Defined Under Namespace

Classes: Array, Base, Boolean, Class, Date, DateTime, Float, Hash, Integer, Nil, Object, Range, Rational, Set, String, Symbol, Time

Class Method Summary collapse

Class Method Details

.coerce(from, to) ⇒ Proc{(Object, Mixture::Types::Object) => Object}

Returns a block that takes one argument: the value.

Parameters:

Returns:



49
50
51
52
53
# 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

.coercersHash{Mixture::Type => Mixture::Coerce::Base}

A hash of the coercers that currently exist. This maps their types to their classes.

Returns:



38
39
40
# File 'lib/mixture/coerce.rb', line 38

def self.coercers
  @_coercers ||= ThreadSafe::Hash.new
end

.finalizevoid

This method returns an undefined value.

Registers the default coercions.



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# 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

.perform(type, value) ⇒ Object

Performs the actual coercion, since blocks require a value and type arguments.

Parameters:

Returns:

  • (Object)

    The coerced value.



61
62
63
64
65
66
67
68
69
70
71
72
73
# 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

.register(coercion) ⇒ void

This method returns an undefined value.

Registers a coercion with the module. This uses the coercers constant.

Parameters:



30
31
32
# File 'lib/mixture/coerce.rb', line 30

def self.register(coercion)
  coercers[coercion.type] = coercion
end