Class: Plumb::Decorator

Inherits:
Object
  • Object
show all
Defined in:
lib/plumb/decorator.rb

Overview

A class to help decorate all or some types in a type composition. Example:

Type = Types::Array[Types::String | Types::Integer]
Decorated = Plumb::Decorator.(Type) do |type|
if type.is_a?(Plumb::ArrayClass)
  LoggerType.new(type, 'array')
else
  type
end
end

The block is called on EVERY node, bottom-up: sub-types are visited (and possibly replaced) before the block sees the node itself. Returning a node unchanged is a no-op, and an unchanged subtree comes back as the identical object.

Traversal is NodeMapper's, so it reaches a record's fields, a container's element type and the inside of a Metadata / Policy / #as_node wrapper. It stops at a Constraint's base (rebuilding one would drop a custom #check message) and at a Deferred (forcing it would loop on a self-referential type).

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(block) ⇒ Decorator

Returns a new instance of Decorator.



31
32
33
# File 'lib/plumb/decorator.rb', line 31

def initialize(block)
  @block = block
end

Class Method Details

.call(type, &block) ⇒ Object



27
28
29
# File 'lib/plumb/decorator.rb', line 27

def self.call(type, &block)
  new(block).visit(type)
end

Instance Method Details

#visit(type) ⇒ Composable

Parameters:

Returns:



37
38
39
# File 'lib/plumb/decorator.rb', line 37

def visit(type)
  decorate(NodeMapper.map(type) { |child| visit(child) })
end