Active Helper Methods - Using a Module Versus Inheritance

Let's say I want to define some methods and helpers that will be available in all my models ActiveRecord.

A little research tells me that there are two common options

Module

Define a module

module MyModule
  def foo
    # ...
  end
end

Include it in the model when you need it

class User < ActiveRecord::Base
  include MyModule

  before_save :foo
end

Inheritance

Define a base class

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

  def foo
    # ...
  end
end

Make all models inherited from it

class User < BaseModel
  include MyModule

  before_save :foo
end

What are the pros and cons for each - are there any special advantages to this? Is there one that was more seen as a "Rails way"?

Thank!

+4
source share
1 answer

/, has, is.

, , Module inheritance. , , 2 , 2 BaseClasses, .

, , , , , has.

, , ,

+6

Source: https://habr.com/ru/post/1628187/


All Articles