Class: Flows::Contract::Transformer

Inherits:
Flows::Contract show all
Defined in:
lib/flows/contract/transformer.rb

Overview

Adds transformation to an existing contract.

If original contract already has a transform - final transformation will be composition of original and new one.

You MUST obey Transformation Laws (see Flows::Contract documentation for details).

Examples:

Upcase strings

up_str = Flows::Contract::Transformer.new(String) { |str| str.upcase }

up_str.transform!('megatron')
# => 'MEGATRON'

up_str.transform(:megatron).error
# => 'must match `String`'

Strip and upcase strings

strip_str =  Flows::Contract::Transformer.new(String, &:strip)
up_stip_str = Flows::Contract::Transformer.new(strip_str, &:upcase)

up_str.transform!('   megatron   ')
# => 'MEGATRON'

up_str.cast(:megatron).error
# => 'must match `String`'

Since:

  • 0.4.0

Instance Method Summary collapse

Methods inherited from Flows::Contract

#===, #check, make, #to_proc, #transform

Constructor Details

#initialize(contract) {|object| ... } ⇒ Transformer

Returns a new instance of Transformer.

Parameters:

  • contract (Contract, Object)

    in case of non-contract argument CaseEq is automatically applied.

Yields:

  • (object)

    transform implementation

Yield Returns:

  • (object)

    result of transform. Must obey transformation laws.

Since:

  • 0.4.0



32
33
34
35
# File 'lib/flows/contract/transformer.rb', line 32

def initialize(contract, &transform_proc)
  @contract = to_contract(contract)
  @transform = transform_proc
end

Instance Method Details

#check!(other) ⇒ Object

See Also:

Since:

  • 0.4.0



38
39
40
# File 'lib/flows/contract/transformer.rb', line 38

def check!(other)
  @contract.check!(other)
end

#transform!(other) ⇒ Object

See Also:

Since:

  • 0.4.0



43
44
45
46
47
# File 'lib/flows/contract/transformer.rb', line 43

def transform!(other)
  @transform.call(
    @contract.transform!(other)
  )
end