Class: Lugg::Filter

Inherits:
Object
  • Object
show all
Defined in:
lib/lugg/filter.rb

Overview

Apply a list of filters to an Enumerable object or an enumerator.

This class is used to combine all the search queries into a single filter to process a collection with. Its input is expected to be a Lugg::Streamer enumerator, but it could be anything.

By default, the collection will be passed through as-is, but you can add more conditions to limit the results with either callable objects (such as Procs) or with blocks.

Examples:

Using a proc

filter = Filter.new
filter.use ->(record) { record.method == 'GET' }

Using a block

filter = Filter.new
filter.use { |record| record.code == 404 }

Instance Method Summary collapse

Constructor Details

#initializeFilter

Returns a new instance of Filter.



20
21
22
# File 'lib/lugg/filter.rb', line 20

def initialize
  @conditions = []
end

Instance Method Details

#call(records) ⇒ Enumerable

Apply all known conditions to records.

Parameters:

  • records (Enumerable)

Returns:

  • (Enumerable)

    filtered records



28
29
30
31
32
33
# File 'lib/lugg/filter.rb', line 28

def call(records)
  return records unless @conditions.any?
  records.select do |record|
    matches?(record)
  end
end

#use(callable = nil, &block) ⇒ Object

Store a new condition to be used on the next invocation of #call.

Parameters:

  • callable (#call) (defaults to: nil)

Raises:

  • ArgumentError when both a callable or block are given

  • ArgumentError when the given callable does not respond to #call



40
41
42
43
44
45
46
47
48
49
50
# File 'lib/lugg/filter.rb', line 40

def use(callable = nil, &block)
  unless block_given? ^ callable
    raise ArgumentError, 'Supply either an argument or a block'
  end

  unless block_given? || callable.respond_to?(:call)
    raise ArgumentError, 'Supply either a callable argument or a block'
  end

  @conditions << (block_given? ? block : callable)
end