Class: DataFilter::LikeFilter

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

Overview

Used to filter a data item by a search term by seeing if the data field value is similar to the search term

Examples:

object = MyModel.new(text: 'hello world!')
filter = DataFilter::LikeFilter.new(:text, 'hello')
filter.call(object)
# => #<MyModel text: 'hello world'>

Instance Method Summary collapse

Constructor Details

#initialize(field_sym, search_term, normalize_regex = nil) ⇒ LikeFilter

Returns a new instance of LikeFilter.

Parameters:

  • field_sym (Symbol)

    name of the data method we want to filter

  • search_term (String)

    the value we want to use when filtering the data item

  • normalize_regex (regex) (defaults to: nil)

    the optional regular expression for normalizing the string to search



17
18
19
20
21
# File 'lib/data_filter/like_filter.rb', line 17

def initialize(field_sym, search_term, normalize_regex = nil)
  @field_sym = field_sym
  @search_term = search_term
  @normalize_regex = normalize_regex || /[^\w\s]/
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



27
28
29
30
31
32
# File 'lib/data_filter/like_filter.rb', line 27

def call(item)
  if item.respond_to?(@field_sym) &&
    match?(item.public_send(@field_sym), @search_term)
    item
  end
end