Class: ContextFilters::Filters

Inherits:
Object
  • Object
show all
Defined in:
lib/context-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

Constructor Details

#initializeFilters

initialize the filters storage



36
37
38
# File 'lib/context-filters/filters.rb', line 36

def initialize
  @filters = {}
end

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



56
57
58
# File 'lib/context-filters/filters.rb', line 56

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

#empty?Boolean

Returns true if there are any rules stored, false otherwise.

Returns:

  • (Boolean)

    true if there are any rules stored, false otherwise



78
79
80
# File 'lib/context-filters/filters.rb', line 78

def empty?
  @filters.empty?
end

#filtersObject

Array of already defined filters



73
74
75
# File 'lib/context-filters/filters.rb', line 73

def filters
  @filters.keys
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



64
65
66
67
68
69
70
# File 'lib/context-filters/filters.rb', line 64

def select_filters(target, options)
  found = @filters.fetch(options, [])
  if   Hash === options
  then found += @filters.fetch(options.merge(:target => target), [])
  end
  found
end

#store(options = nil, &block) ⇒ Object

stores the block for given options, if the options have a block already the new one is added to the list

Parameters:

  • options (Object) (defaults to: nil)

    options for filtering blocks

  • block (Proc)

    block of code to add to the list of blocks for this options



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

def store(options = nil, &block)
  @filters[options] ||= []
  @filters[options] << block
end