Module: Filtration

Included in:
Object
Defined in:
lib/filtration.rb

Instance Method Summary collapse

Instance Method Details

#postfilter(method, filter = nil, &block) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/filtration.rb', line 21

def postfilter(method, filter=nil, &block)
  old_method = instance_method(method)
  raise "Method #{method} takes 0 arguments" if old_method.arity == 0

  raise "Cannot use both filter method and block" if !filter.nil? && !block.nil?
  raise "Block or filter method missing" if filter.nil? && block.nil?

  define_method(method) do |*args|
    if filter.nil?
      block.call(old_method.bind(self).call(*args))
    else
      filter_method = method(filter)
      raise "Filter method #{filter} takes 0 arguments" if filter_method.arity == 0
      self.send(filter,old_method.bind(self).call(*args))
    end
  end
end

#prefilter(method, filter = nil, &block) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/filtration.rb', line 3

def prefilter(method, filter=nil, &block)
  old_method = instance_method(method)
  raise "Method #{method} takes 0 arguments" if old_method.arity == 0

  raise "Cannot use both filter method and block" if !filter.nil? && !block.nil?
  raise "Block or filter method missing" if filter.nil? && block.nil?

  define_method(method) do |*args|
    if filter.nil?
      old_method.bind(self).call(block.call(*args))
    else
      filter_method = method(filter)
      raise "Filter method #{filter} takes 0 arguments" if filter_method.arity == 0
      old_method.bind(self).call(self.send(filter,*args))
    end
  end
end