Refactoring ActiveRecord models with a base class versus a base module

前端 未结 5 1317
执念已碎
执念已碎 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 08:56

    You have more flexibility with the module. The module's intent is to span across different types of classes. With the other method you are locking yourself into Base. Other than that, there isn't much difference.

    Ruby's answer to multiple inheritance is mixins. Since your classes are already inheriting from Rails specific classes, they can no longer inherit from your custom classes.

    So your choice is to chain together in a long chain, or use a mixin which is much cleaner, and easier to understand.

提交回复
热议问题