サブクラスの各メソッドの後に 1 つのメソッド呼び出しをラップする、ある種のモジュールまたはスーパークラスを作成しようとしています。ただし、いくつかの制約があります。initialize() が呼び出された後や、選択した他のいくつかのメソッドが呼び出された後にメソッドを実行したくありません。もう 1 つの制約は、フラグ@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