Class: Croesus::Coercer

Inherits:
Object show all
Defined in:
lib/croesus/coerce.rb

Overview

The class that coerces objects based on the definitions that are registered with it.

Instance Method Summary collapse

Constructor Details

#initializeCoercer

Returns a new instance of Coercer.


24
25
26
27
28
29
30
31
# File 'lib/croesus/coerce.rb', line 24

def initialize
  @coercions = Hash.new do |hash, origin|
    hash[origin] = Hash.new do |h, target|
      h[target] = Coercion.new(origin, target)
    end
  end
  @mutex = Mutex.new
end

Instance Method Details

#coerce(object, target) ⇒ Object

Parameters:

  • object (Object)

    the object to coerce

  • target (Class)

    what you want the object to turn in to


57
58
59
60
61
# File 'lib/croesus/coerce.rb', line 57

def coerce(object, target)
  @mutex.synchronize do
    @coercions[object.class][target].call(object)
  end
end

#register(origin, target, &block) ⇒ Object

Registers a coercion with the Croesus library

Parameters:

  • origin (Class)

    the class to convert

  • target (Class)

    what the origin will be converted to

Raises:

  • (ArgumentError)

37
38
39
40
41
42
43
# File 'lib/croesus/coerce.rb', line 37

def register(origin, target, &block)
  raise(ArgumentError, 'block is required') unless block_given?

  @mutex.synchronize do
    @coercions[origin][target] = Coercion.new(origin, target, &block)
  end
end

#unregister(origin, target) ⇒ Object

Removes a coercion from the library

Parameters:

  • origin (Class)
  • target (Class)

49
50
51
52
53
# File 'lib/croesus/coerce.rb', line 49

def unregister(origin, target)
  @mutex.synchronize do
    @coercions[origin].delete(target)
  end
end