永远记住:Ruby中几乎所有内容都有一个回调。
尝试以下操作:
module MyOwnPlugin
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
# gets called from within the models
def acts_as_my_own_plugin(options)
# store the list of methods in a class variable and symbolize them
@@methods = []
options[:methods].each { |method| @@methods << method.to_sym }
end
# callback method. gets called by ruby if a new method is added.
def method_added(name_of_method)
if @@methods.include?(name_of_method)
# delete the current method from our @@methods array
# in order to avoid infinite loops
@@methods.delete(name_of_method)
#puts "DEBUG: #{name_of_method.to_s} has been added!"
# code from your original plugin
self.class_eval <<-END
alias_method :origin_#{name_of_method}, :#{name_of_method}
def #{name_of_method}
puts "Called #{name_of_method}"
origin_#{name_of_method}
end
END
end
end
end
end
# include the plugin module in ActiveRecord::Base
# in order to make acts_as_my_own_plugin available in all models
ActiveRecord::Base.class_eval do
include MyOwnPlugin
end
# just call acts_as_my_own_plugin and define your methods afterwards
class Foo < ActiveRecord::Base
acts_as_my_own_plugin :methods => [:bar]
def bar
puts 'do something'
end
end
我希望这是有用的。你能用Ruby做的疯狂的事情很酷;)
如果要允许在调用之前和之后定义方法,
acts_as_my_own_plugin
您需要再次更改代码以允许这样做。然而,困难的部分已经完成了。
免责声明:这已经用Ruby1.8.7测试过了。可能不适用于Ruby 1.9.*。