Does ruby have “hooks”. Where I can define, let’s say, a method called
__before that will be called before ANY method call for that class?
Thanks for your help.
Does ruby have “hooks”. Where I can define, let’s say, a method called
__before that will be called before ANY method call for that class?
Thanks for your help.
You can do it easily this way (depending what you really want):
def lady
puts “ladies go first”
end
class Myclass
lady
def initialize
end
def man
puts “you look better from here”
end
end
myclass=Myclass.new
myclass.man
/–> ladies go first
/–> you look better from here
A not OO solution is to use:
(from programming ruby book)
Every Ruby source file can declare blocks of code to be run as the file
is being loaded (the BEGIN blocks) and after the program has finished
executing (the END blocks).
BEGIN {
begin code
}
END {
end code
}
A program may include multiple BEGIN and END blocks. BEGIN blocks are
executed in the order they are encountered. END blocks are executed in
reverse order.
hope it helps
-rb.
Hi,
On Saturday 10 February 2007 20:17, Ben J. wrote:
Does ruby have “hooks”. Where I can define, let’s say, a method called
__before that will be called before ANY method call for that class?
maybe this decorator will fit:
require ‘blank’ # Parked at Loopia
module Decorator
def self.decorate real_class, &block
slate = Blank()
slate.class_eval do
define_method(:real_class) { real_class }
def initialize
@_object = real_class.new
end
def method_missing meth, *args, &block
@_object.send meth, *args, &block
end
end
slate.class_eval &block
slate
end
end
module Kernel
def Decorate klass, &block
Decorator.decorate klass, &block
end
end
class A
def a; ‘a’ end
end
with_before_hook = Proc.new {
protected
def before_hook meth, *args, &block
STDOUT.puts "before #{meth}: " << “%s %s” % [args.inspect,
block.inspect]
end
def method_missing meth, *args, &block
before_hook meth, *args, &block
@_object.send meth, *args, &block
end
}
B = Decorate A, &with_before_hook
a = B.new
before inspect: [] nil
=> #<A:0xb7b8b05c>
a.class
before class: [] nil
=> A
a.methods
before methods: [] nil
=> [“enum_for”, “inspect”, “send”, "taguri…
but maybe this module is too general for this specific purpouse, but it
can
also be adapted by adding singleton class methods like self.before() and
self.after() in the initialize, and arrange them to automatically
replace
method_missing with an “hooked” one. or hooks can be explicitely coded
into
the main method_missing… you choose.
How about using a decorator pattern?
Here is a good example of one:
http://www.lukeredpath.co.uk/2006/9/6/decorator-pattern-with-ruby-in-8-lines
Follow the instructions and then change the method_missing method to
taste.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs