Class: DataFilter::TruthyFilter

Inherits:
Object
  • Object
show all
Defined in:
lib/data_filter/truthy_filter.rb

Overview

Used to filter a data item by whether it is truthy/falsey

Examples:

object = MyModel.new(is_alive: 'false')
filter = DataFilter::TruthyFilter.new(:is_alive)
filter.call(object)
# => nil

Instance Method Summary collapse

Constructor Details

#initialize(field_sym, invert: false) ⇒ TruthyFilter

Returns a new instance of TruthyFilter.

Parameters:

  • field_sym (Symbol)

    the name of the field to filter by

  • invert (Boolean) (defaults to: false)

    (default: false) set to true if you would rather match when the field is falsey instead of when it is truthy



14
15
16
17
# File 'lib/data_filter/truthy_filter.rb', line 14

def initialize(field_sym, invert: false)
  @field_sym = field_sym
  @invert = invert
end

Instance Method Details

#call(item) ⇒ Object?

Filters the item

Parameters:

  • item (Object)

    the item we want to filter

Returns:

  • (Object, nil)

    the original data item



23
24
25
26
27
28
29
30
31
32
# File 'lib/data_filter/truthy_filter.rb', line 23

def call(item)
  if item.respond_to?(@field_sym)
    val = item.public_send(@field_sym)
    is_falsey = is_falsey?(val)
    is_match = (@invert ? is_falsey : !is_falsey)
    if is_match
      item
    end
  end
end