Refactoring ActiveRecord models with a base class versus a base module

前端 未结 5 1312
执念已碎
执念已碎 2021-02-04 08:22

Class A and B are identical:

class A < ActiveRecord::Base
 def foo
  puts \"foo\"
 end
end

class B < ActiveRecord::Base
 def foo
  puts \"foo\"
 end
end
<         


        
5条回答
  •  北海茫月
    2021-02-04 09:07

    Both of these methods will work. When deciding to use a module or a class, the question I have is does the class fit into the object hierarchy, or are these just methods I am looking to reuse. If I am just trying to factor out common code for DRY reasons, that sounds like a module. If there really is a class that fits into the hierarchy that makes sense on its own, I use a class.

    Coming from a Java background, it is refreshing I can choose to make these decisions.

提交回复
热议问题