Class: Kiba::Extend::Transforms::FilterRows::WithLambda

Inherits:
Object
  • Object
show all
Includes:
ActionArgumentable
Defined in:
lib/kiba/extend/transforms/filter_rows/with_lambda.rb

Overview

Keep or reject rows based on whether the arbitrary Lambda passed in evaluates to true/false

Examples

Source data:

{a: 'a', b: 'b', c: 'c' },
{a: 'a', b: 'b', c: '' },
{a: '', b: nil, c: 'c' },
{a: '', b: 'b', c: 'c' },
{a: '', b: nil, c: nil },

Used in pipeline as:

logic = ->(row){ row.values.any?(nil) }
transform FilterRows::WithLambda, action: :keep, lambda: logic

Resulting data:

{a: '', b: nil, c: 'c' },
{a: '', b: nil, c: nil }

Used in pipeline as:

whatever = ->(x) do
  x.values.any?(nil)
end
transform FilterRows::WithLambda, action: :keep, lambda: whatever

Resulting data:

{a: 'a', b: 'b', c: 'c' },
{a: 'a', b: 'b', c: '' },
{a: '', b: 'b', c: 'c' },

The following will raise a NonBooleanLambdaError because logic returns an Array, rather than TrueClass or FalseClass:

logic = ->(row){ row.values.select{ |val| val.nil? } }
transform FilterRows::WithLambda, action: :keep, lambda: logic

Raises:

Since:

  • 2.9.0

Instance Method Summary collapse

Constructor Details

#initialize(action:, lambda:) ⇒ WithLambda

Returns a new instance of WithLambda.

Parameters:

  • action (:keep, :reject)

    what to do with row matching criteria

  • lambda (Lambda)

    with one parameter for row to be passed in through. The Lambda must evaulate to/return TrueClass or FalseClass

Since:

  • 2.9.0



73
74
75
76
77
78
# File 'lib/kiba/extend/transforms/filter_rows/with_lambda.rb', line 73

def initialize(action:, lambda:)
  validate_action_argument(action)
  @action = action
  @lambda = lambda
  @lambda_tested = false
end

Instance Method Details

#process(row) ⇒ Object

Parameters:

  • row (Hash{ Symbol => String, nil })

Since:

  • 2.9.0



81
82
83
84
85
86
87
88
89
90
# File 'lib/kiba/extend/transforms/filter_rows/with_lambda.rb', line 81

def process(row)
  test_lambda(row) unless lambda_tested

  case action
  when :keep
    row if lambda.call(row)
  when :reject
    row unless lambda.call(row)
  end
end