The title sounds rediculous because it is. My biggest issue is actually trying to figure out what question to ask.
T开发者_运维技巧he goal: To be able to implement the code as described below OR to figure out what terminology I should be using to search for the correct answer.
The issue: I wish to have a system where classes register "processors" via a method within the class definition. eg:
class RunTheseMethodsWhenICallProcess Include ProcessRunner add_processor :a_method_to_run add_processor :another_method_to_run def a_method_to_run puts "This method ran" end def another_method_to_run puts "another method ran" end end Module ProcessRunner def process processors.each {|meth| self.send(meth)} end end
My issues are mostly with understanding the scope and reference of the class to make them interact. As it stands, I have been able to add a static method 'add_processor' by calling class.extend(AClass) in the included method and adding in the class there.
The idea for this syntax was inspired by DataMappers 'property' and 'before' methods. Even with the code checked out, I am having a touch of trouble following it.
Thanks so much for any help you can offer.
If I got you right, the following will do what you want.
It initializes each class (or module) including ProcessRunner
to have an empty array in @@processors
. Additionally it adds class methods processors
(a simple getter) and add_processor
.
The process
method had to be adjusted to use the class method. In fact, you could add a wrapper for this, but I think that would be to verbose for such a sample.
module ProcessRunner
module ClassMethods
def add_processor(processor)
processors << processor
end
def processors
class_variable_get :@@processors
end
end
def self.included(mod)
mod.send :class_variable_set, :@@processors, []
mod.extend ClassMethods
end
def process
self.class.processors.each {|meth| self.send(meth)}
end
end
class RunTheseMethodsWhenICallProcess
include ProcessRunner
add_processor :a_method_to_run
add_processor :another_method_to_run
def a_method_to_run
puts "This method ran"
end
def another_method_to_run
puts "another method ran"
end
end
精彩评论