lib/method_found/interceptor.rb in method_found-0.1.3 vs lib/method_found/interceptor.rb in method_found-0.1.4
- old
+ new
@@ -25,20 +25,20 @@
@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)
+ 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)
+ if matches = matcher_.match(method_name, self)
method_cacher.(method_name, matches)
else
super(method_name, include_private)
end
end
@@ -51,30 +51,38 @@
end
private
def cache_method(method_name, matches)
- intercept_method = @intercept_method
+ intercept_method, matcher = @intercept_method, @matcher
define_method method_name do |*arguments, &block|
- send(intercept_method, method_name, matches, *arguments, &block)
+ if matcher.proc? && !(matches = matcher.match(method_name, self))
+ return super(*arguments, &block)
+ end
+ arguments = [matches, *arguments] unless method(intercept_method).arity == 1
+ send(intercept_method, method_name, *arguments, &block)
end
end
def assign_intercept_method(&intercept_block)
@intercept_method ||= "__intercept_#{SecureRandom.hex}".freeze.tap do |method_name|
define_method method_name, &intercept_block
end
end
class Matcher < Struct.new(:matcher)
- def match(method_name)
+ def match(method_name, context)
if matcher.is_a?(Regexp)
matcher.match(method_name)
elsif matcher.respond_to?(:call)
- matcher.call(method_name) && [method_name.to_s]
+ context.instance_exec(method_name, &matcher)
else
- (matcher.to_sym == method_name) && [method_name.to_s]
+ (matcher.to_sym == method_name)
end
+ end
+
+ def proc?
+ matcher.is_a?(Proc)
end
def inspect
matcher.inspect
end