我正在尝试编写一个插件,以下列方式对 ActiveRecord 中的某些方法进行别名:
class Foo < ActiveRecord::Base
include MyOwnPlugin
acts_as_my_own_plugin :methods => [:bar]
def bar
puts 'do something'
end
end
插件内部:
module MyOwnPlugin
def self.included(base)
base.class_eval do
extend ClassMethods
end
end
module ClassMethods
def acts_as_my_own_plugin(options)
options[:methods].each do |m|
self.class_eval <<-END
alias_method :origin_#{m}, :#{m}
END
end
end
end
end
这种方法不起作用,因为当 #acts_as_my_own_plugin 运行时, Foo#bar 尚未定义,因为它尚未运行。
将acts_as_my_own_plugin :methods => [:bar]放在bar 函数声明之后将起作用。然而,这并不漂亮。
我希望能够像大多数插件一样将acts_as_my_own_plugin 放在类定义的顶部。
是否有替代方法来满足此条件?