JP.*_*JP. 1 ruby methods class
我想跟踪在我构建的类的实例上运行的所有方法.
目前我这样做:
class MyClass
def initialize
@completed = []
end
# Sends a welcome and information pack to the person who requested it
def one_of_many_methods
unless @completed.include? __method__
# Do methody things
@completed.push __method__
end
end
alias :another_name :one_of_many_methods
# Calling myClassInstance.another_name will insert
# :one_of_many_methods into @completed.
# Methody things should not now be done if .another_name
# or .one_of_many_methods is called.
end
Run Code Online (Sandbox Code Playgroud)
但是当我在班上有很多方法时,这会非常费力.我在重复自己!有没有办法跟踪被调用的方法,并且只允许它们被调用一次,就像我上面所做的那样,但是不必在每个方法中重复那个块?
谢谢!
(PS.我正在使用Ruby 1.9)
这听起来像是Proxy对象的完美用例.幸运的是,Ruby的动态性使得实现起来非常简单:
class ExecuteOnceProxy
def initialize(obj)
@obj = obj
@completed = []
end
def method_missing(method, *args)
unless @completed.include?(method)
args.empty? ? @obj.send(method) : @obj.send(method, args)
@completed << method
end
end
end
Run Code Online (Sandbox Code Playgroud)
只需在构造函数中传递原始对象即可初始化代理:
proxy = ExecuteOnceProxy.new(my_obj)
Run Code Online (Sandbox Code Playgroud)