서브 클래스의 각 메소드 후에 하나의 메소드 호출을 감싸는 일종의 모듈 또는 수퍼 클래스를 작성하려고합니다. 그러나 몇 가지 제약 조건이 있습니다 : 나는 initialize()가 호출 된 후에도 메소드가 실행되는 것을 원하지 않으며, 다른 선택 방법이 호출 된 후에도 메소드를 실행하지 않을 것입니다. 또 다른 제약은 깃발 @check_ec이 true로 설정된 경우에만 해당 메서드를 실행하기를 원합니다. 나는 60 개가 넘는 메서드를 가진 클래스를 가지고 있으며, 여기에는 모든 곳으로 압축 된 동일한 코드 조각이 하드 코딩되어 있습니다. 클래스 메서드에 대해 해당 메서드를 자동으로 실행하는 래퍼를 만들 수있는 방법이 있습니까? 어떤이에 대한Ruby - 클래스의 대부분의 메소드 다음에 동일한 코드 실행
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
콜럼버스 달걀을! 간단하고 아름다운. :) – jaeheung
이것은 굉장합니다! 내 문제를 우아한 방식으로 해결했습니다! – Unglued