Class: MethodFound::Interceptor

Inherits:
Module
  • Object
show all
Defined in:
lib/method_found/interceptor.rb

Overview

Class for intercepting method calls using method_missing. Initialized by passing in a matcher object which can be a Regexp, a proc or lambda, or a string/symbol.

Direct Known Subclasses

AttributeInterceptor

Defined Under Namespace

Classes: Matcher

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(matcher = nil, &intercept_block) ⇒ Interceptor

Creates an interceptor module to include into a class.

Parameters:

  • matcher (Regexp, Proc, String, Symbol) (defaults to: nil)

    Matcher for intercepting method calls.



14
15
16
# File 'lib/method_found/interceptor.rb', line 14

def initialize(matcher = nil, &intercept_block)
  define_method_missing(matcher, &intercept_block) unless matcher.nil?
end

Instance Attribute Details

#matcherObject (readonly)

Returns the value of attribute matcher.



10
11
12
# File 'lib/method_found/interceptor.rb', line 10

def matcher
  @matcher
end

Instance Method Details

#define_method_missing(matcher) {|method_name, matches, &block| ... } ⇒ Object

Define method_missing and respond_to_missing? on this interceptor. Can be called after interceptor has been created.

Parameters:

  • matcher (Regexp, Proc, String, Symbol)

    Matcher for intercepting method calls.

Yields:

  • (method_name, matches, &block)

    Yiels method_name matched, set of matches returned from matcher, and block passed to method when called.



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/method_found/interceptor.rb', line 24

def define_method_missing(matcher, &intercept_block)
  @matcher = matcher_ = Matcher.new(matcher)
  assign_intercept_method(&intercept_block)
  method_cacher = method(:cache_method)

  define_method :method_missing do |method_name, *arguments, &method_block|
    if matches = matcher_.match(method_name, self)
      method_cacher.(method_name, matches)
      send(method_name, *arguments, &method_block)
    else
      super(method_name, *arguments, &method_block)
    end
  end

  define_method :respond_to_missing? do |method_name, include_private = false|
    if matches = matcher_.match(method_name, self)
      method_cacher.(method_name, matches)
    else
      super(method_name, include_private)
    end
  end
end

#inspectObject



47
48
49
50
51
# File 'lib/method_found/interceptor.rb', line 47

def inspect
  klass = self.class
  name  = klass.name || klass.inspect
  "#<#{name}: #{matcher.inspect}>"
end