如题:如何实现一个 before_filter 功能?刚刚找的一段代码:
module Filter
def before_filter name
@@filter = name
end
def method_added name
return if @filtering
return if @@filter == name
return if name == :initialize
@filtering = true
alias_method :"original_#{name}", name
define_method name do |*args|
self.send @@filter
self.send :"original_#{name}", *args
end
@filtering = false
end
end
class Test
extend Filter
before_filter :logger
def foo
puts "call #{__method__}"
end
private
def logger
puts "logging..."
end
end
Ruby 版本无限定,可以使用最新的 2.x, 希望大家分享下您的方法?