Ruby on Rails 3.2.9 と Ruby 1.9.3 を使用しています。次のような同様のメソッドを実装する多くのモデル クラスがあります。
class ClassName_1 < ActiveRecord::Base
def great_method
self.method_1
end
def method_1 ... end
end
class ClassName_2 < ActiveRecord::Base
def great_method
result_1 = self.method_1
result_2 = self.method_2
result_1 && result_2
end
def method_1 ... end
def method_2 ... end
end
...
class ClassName_N < ActiveRecord::Base
def great_method
result_1 = self.method_1
result_2 = self.method_2
...
result_N = self.method_N
result_1 && result_2 && ... && result_N
end
def method_1 ... end
def method_2 ... end
...
def method_N ... end
end
これらのモデル クラスは、ほとんど同じ (同じではない) 動作をします。すべてのメソッドの名前は異なります (たとえば、名前を付けるmethod_1
ことができ、名前bar
をmethod_2
付けることができますfoo
)。すべての returntrue
またはfalse
は、各クラスで常に同じであり、それらの間に関係はありません。
これらのクラスをリファクタリングする適切な方法は何ですか?
注:現時点では、各クラスに次のモジュールを含めることでクラスをリファクタリングすることを考えています。
module MyModule
def great_method
result_1 = self.respond_to?(:method_1) ? self.method_1 : true
result_2 = self.respond_to?(:method_2) ? self.method_2 : true
...
result_N = self.respond_to?(:method_N) ? self.method_N : true
result_1 && result_2 && ... && result_N
end
end
しかし、それが私が探していることを達成するための適切な方法であるかどうかはわかりません。さらに、関連する長所と短所はわかりません...