Class: ContextFilters::Filters::Filters

Inherits:
Object
  • Object
show all
Includes:
Store
Defined in:
lib/context-filters/filters/filters.rb

Overview

Store and apply filters using blocks

Examples:


class FiltersTestSubject
  attr_reader :value
  def initialize(value)
    @value = value
  end
  def change(&block)
    @value = block.call(@value)
  end
end
filters = ContextFilters::Filters.new
filters.store(:addition) {|value| value + 1 }
filters.store(:subtraction) {|value| value - 1 }
filters.filters # => [:addition, :subtraction]
object = FiltersTestSubject.new(3)
object.value => 3
filters.apply(object.method(:change), :addition)
object.value => 4
filters.apply(object.method(:change), :subtraction)
object.value => 3

Instance Method Summary collapse

Methods included from Store

#empty?, #filters, #filters_store, #store

Instance Method Details

#apply(target, method, options = nil) ⇒ Object

applies matching filters to the given target method, also uses filters matching extra :target => target when options is a Hash

Parameters:

  • target (Object)

    an object to run the method on

  • method (symbol)

    method name that takes a transformation block as param

  • options (Object) (defaults to: nil)

    a filter for selecting matching blocks



46
47
48
# File 'lib/context-filters/filters/filters.rb', line 46

def apply(target, method, options = nil)
  select_filters(target, options).each{|block| target.send(method, &block) }
end

#select_filters(target, options) ⇒ Object

Select matching filters and filters including targets when options is a Hash

Parameters:

  • target (Object)

    an object to run the method on

  • options (Object)

    a filter for selecting matching blocks



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/context-filters/filters/filters.rb', line 54

def select_filters(target, options)
  found = filters_store.fetch(options, [])
  if
    Hash === options || options.nil?
  then
    options ||={}
    options.merge!(:target => target)
    found +=
    # can not @filters.fetch(options, []) to allow filters provide custom ==()
    filters_store.select do |filter_options, filters|
      options == filter_options
    end.map(&:last).flatten
  end
  found
end