Active Record辅助方法 - 使用模块与继承

use*_*003 4 inheritance activerecord ruby-on-rails

假设我想定义一些可以在我所有ActiveRecord模型中使用的方法和助手.

一些研究告诉我有两种一般选择

模

定义一个模块

module MyModule
  def foo
    # ...
  end
end
Run Code Online (Sandbox Code Playgroud)

在需要时将其包含在模型中

class User < ActiveRecord::Base
  include MyModule

  before_save :foo
end
Run Code Online (Sandbox Code Playgroud)

遗产

定义基类

class BaseModel < ActiveRecord::Base
  # Define as abstract so AR doesn't assume there's a table named `base_models`
  self.abstract_class = true

  def foo
    # ...
  end
end
Run Code Online (Sandbox Code Playgroud)

让所有模型继承自它

class User < BaseModel
  include MyModule

  before_save :foo
end
Run Code Online (Sandbox Code Playgroud)

每个人的利弊是什么 - 以一种方式做到这一点有什么特别的优势吗?有没有更多的人认为是"Rails方式"?

谢谢!

Ner*_*min 6

它始终是更好地使用类/模块被称为关系has,而不是关闭is.

或者换句话说,最好使用Module相反的inheritance.这是因为后面可能的变化,如果你以后要求有2种类型的类,你必须创建2 BaseClasses,并让一些类继承一个,而另一个继承.

当您使用模块时,您只需包含模块,从而定义包含它的类的行为,即所谓的has行为.

为了更好地掌握代码中的优点和不熟悉代码,学习模式,阅读清洁代码