Class: Mixture::Coerce::Base

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/mixture/coerce/base.rb

Overview

The base for coercion actions. Each action defines the “from” type, and the instance handles the “to”.

Direct Known Subclasses

Array, Date, DateTime, Float, Hash, Integer, Nil, Object, Rational, Set, String, Symbol, Time

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.coerce_to(to, value = Undefined, &block) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/mixture/coerce/base.rb', line 33

def self.coerce_to(to, value = Undefined, &block)
  fail ArgumentError, "Expected Mixture::Type, got #{to.class}" unless
    to.is_a?(Mixture::Type)

  body = case
         when value != Undefined
           value.to_proc
         when block_given?
           block
         else
           fail ArgumentError, "Expected a block"
         end

  coercions[to] = to.method_name
  define_method(to.method_name) { body }
end

.coercionsObject



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

def self.coercions
  @_coercions ||= {}
end

.to(type) ⇒ Object



50
51
52
# File 'lib/mixture/coerce/base.rb', line 50

def self.to(type)
  instance.to(type)
end

.type(value = Undefined) ⇒ Object



21
22
23
24
25
26
27
# File 'lib/mixture/coerce/base.rb', line 21

def self.type(value = Undefined)
  if value == Undefined
    @_type
  else
    @_type = value
  end
end

Instance Method Details

#to(type) ⇒ Object



54
55
56
57
58
59
60
61
# File 'lib/mixture/coerce/base.rb', line 54

def to(type)
  method_name = self.class.coercions.fetch(type) do
    fail CoercionError,
         "Undefined coercion of #{self.class.type} => #{type}"
  end

  public_send(method_name)
end

#type(value) ⇒ void

This method returns an undefined value.

Sets the type this instance corresponds to.

Parameters:



21
22
23
24
25
26
27
# File 'lib/mixture/coerce/base.rb', line 21

def self.type(value = Undefined)
  if value == Undefined
    @_type
  else
    @_type = value
  end
end