Class: Yukata::Coercer

Inherits:
Object
  • Object
show all
Defined in:
lib/yukata/coercer.rb

Overview

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

Author:

  • Matthew A. Johnston

Instance Method Summary collapse

Constructor Details

#initializeCoercer

Returns a new instance of Coercer.



7
8
9
10
11
12
13
14
# File 'lib/yukata/coercer.rb', line 7

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



40
41
42
43
44
# File 'lib/yukata/coercer.rb', line 40

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 yukata library

Parameters:

  • origin (Class)

    the class to convert

  • target (Class)

    what the origin will be converted to

Raises:

  • (ArgumentError)


20
21
22
23
24
25
26
# File 'lib/yukata/coercer.rb', line 20

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)


32
33
34
35
36
# File 'lib/yukata/coercer.rb', line 32

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