Skip to content

Instantly share code, notes, and snippets.

@gnufied
Created September 8, 2011 15:08
Show Gist options
  • Save gnufied/1203631 to your computer and use it in GitHub Desktop.
Save gnufied/1203631 to your computer and use it in GitHub Desktop.
require "rubygems"
require "active_support"
class CutPoint
def self.monitor(monitored_klass)
@local_instance = new()
@monitored_klass = monitored_klass
class << monitored_klass
cattr_accessor :local_instance
end
@monitored_klass.local_instance = @local_instance
end
def self.before(options = {})
methods = Array.wrap(options[:calls_to])
intercept = options[:call]
methods.each do |method_name|
@monitored_klass.class_eval do
alias_method "__original_cut__#{method_name}__", method_name
end
method_body =<<-EOF
def #{method_name}(*args,&block)
self.class.local_instance.#{intercept}(self,args)
__original_cut__#{method_name}__(*args,&block)
end
EOF
@monitored_klass.class_eval(method_body,__FILE__, __LINE__ + 1)
end
end
end
class Foo
def hello(message)
puts message.upcase
end
def my_name
puts "Calling my name"
end
def wow
name = yield
puts "My name is #{name}"
end
end
class Bleh < Foo
def wow
end
end
class FooPoint < CutPoint
monitor Foo
before(:calls_to => [:hello,:my_name,:wow], :call => :hello)
def hello obj,args
puts "Calling hello method"
end
end
a = Bleh.new()
a.hello("Wow")
a.my_name()
a.wow { 'hemant' }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment