Class: Garcon::Coercer

Inherits:
Object show all
Defined in:
lib/garcon/chef/coerce/coercer.rb

Instance Method Summary collapse

Constructor Details

#initializeCoercer

Coerces objects based on the definitions that are registered.



35
36
37
38
39
40
41
42
# File 'lib/garcon/chef/coerce/coercer.rb', line 35

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.



78
79
80
81
82
# File 'lib/garcon/chef/coerce/coercer.rb', line 78

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 Garcon library.

Parameters:

  • origin (Class)

    The class to convert.

  • target (Class)

    What the origin will be converted to.

Raises:

  • (ArgumentError)


52
53
54
55
56
57
58
# File 'lib/garcon/chef/coerce/coercer.rb', line 52

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)


66
67
68
69
70
# File 'lib/garcon/chef/coerce/coercer.rb', line 66

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