我正在尝试创建某种模块或超类,在子类的每个方法之后包装一个方法调用。但是有一些限制:我不希望在调用 initialize() 之后运行该方法,也不希望在调用我选择的其他一些方法之后运行该方法。另一个限制是我只希望在@check_ec标志设置为 true 时执行该方法。我有超过 60 种方法的类,我对粘贴在各处的同一段代码进行了硬编码。有没有办法可以制作一个包装器,为我的类方法自动执行该方法?
所以想法是这样的:
class Abstract
def initialize(check_ec)
@check_ec = check_ec
end
def after(result) # this is the method that I'd like to be added to most methods
puts "ERROR CODE: #{result[EC]}"
end
def methods(method) # below each method it would execute after
result = method() # execute the given method normally
after(result) if @check_ec and method != :initialize and method != :has_valid_params
end
end
class MyClass < Abstract
def initialize(name, some_stuff, check_error_code)
# do some stuff...
@name = name
super(check_error_code)
end
def my_method_a() # execute after() after this method
return {EC: 0}
end
def my_method_b() # execute after() after this method
return {EC: 7}
end
def has_valid_params() # don't execute after() on this method
return true
end
end