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

Inherits:
Object
  • Object
show all
Includes:
ActionArgumentable, BooleanLambdaParamable
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:

Keeping rows with nil values

# Used in pipeline as:
# transform FilterRows::WithLambda,
#   action: :keep,
#   lambda: ->(row) { row.values.any?(nil) }
xform = FilterRows::WithLambda.new(
  action: :keep,
  lambda: ->(row) { row.values.any?(nil) }
)

input = [
  {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}
]
result = Kiba::StreamingRunner.transform_stream(input, xform)
  .map{ |row| row }
expected = [
  {a: "", b: nil, c: "c"},
  {a: "", b: nil, c: nil}
]
expect(result).to eq(expected)

Rejecting rows with nil values

# Used in pipeline as:
# transform FilterRows::WithLambda,
#   action: :reject,
#   lambda: ->(row) { row.values.any?(nil) }
xform = FilterRows::WithLambda.new(
  action: :reject,
  lambda: ->(row) { row.values.any?(nil) }
)

input = [
  {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}
]
result = Kiba::StreamingRunner.transform_stream(input, xform)
  .map{ |row| row }
expected = [
  {a: "a", b: "b", c: "c"},
  {a: "a", b: "b", c: ""},
  {a: "", b: "b", c: "c"}
]
expect(result).to eq(expected)

When Lambda does not evaluate to true/false

row = {a: "a", b: "b", c: "c"}
expect{
  FilterRows::WithLambda.new(action: :keep, lambda: ->(row) { [] })
  .process(row)
}.to raise_error(Kiba::Extend::BooleanReturningLambdaError)

Raises:

Since:

  • 2.9.0

Instance Method Summary collapse

Methods included from BooleanLambdaParamable

included, #lambda_tested, #test_lambda

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



80
81
82
83
84
# File 'lib/kiba/extend/transforms/filter_rows/with_lambda.rb', line 80

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

Instance Method Details

#process(row) ⇒ Object

Parameters:

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

Since:

  • 2.9.0



87
88
89
90
91
92
93
94
95
96
# File 'lib/kiba/extend/transforms/filter_rows/with_lambda.rb', line 87

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