Module: Transproc::Conditional

Extended by:
Functions
Defined in:
lib/transproc/conditional.rb

Overview

Conditional transformation functions

Examples:

require 'transproc/conditional'

include Transproc::Helper

fn = t(:guard, -> s { s.is_a?(::String) }, -> s { s.to_sym })

[fn[2], fn['Jane']]
# => [2, :Jane]

Instance Method Summary collapse

Methods included from Functions

method_added

Instance Method Details

#guard(value, predicate, fn) ⇒ Mixed

Apply the transformation function to subject if the predicate returns true, or return un-modified

Examples:

[2, 'Jane'].map do |subject|
  Transproc(:guard, -> s { s.is_a?(::String) }, -> s { s.to_sym })[subject]
end
# => [2, :Jane]

Parameters:

  • (Mixed)

Returns:

  • (Mixed)


31
32
33
# File 'lib/transproc/conditional.rb', line 31

def guard(value, predicate, fn)
  predicate[value] ? fn[value] : value
end

#is(value, type, fn) ⇒ Object

Calls a function when type-check passes

Examples:

fn = Transproc(:is, Array, -> arr { arr.map(&:upcase) })
fn.call(['a', 'b', 'c']) # => ['A', 'B', 'C']

fn = Transproc(:is, Array, -> arr { arr.map(&:upcase) })
fn.call('foo') # => "foo"

Parameters:

  • (Object)
  • (Class)
  • (Proc)

Returns:

  • (Object)


51
52
53
# File 'lib/transproc/conditional.rb', line 51

def is(value, type, fn)
  guard(value, -> v { v.is_a?(type) }, fn)
end