ruby on rails - What is the preferred way to add some method in active record base? -


I want to create a module that provides some common methods for classes inherited from an active record base.

After two ways we can get it.

1)

  Module Commentable def self.extended (base) includes base.class_eval InstanceMethods Extension ClassMethods End End Module ClassMethods def say 'test class method' test_commentable_classmethod end End module instancemethods def says 'test example method' end end end ActiveRecord :: Base.extend (commentable) test_commentable_instance_method  

2)

  module Commentable def Self.included (base) base.extend (ClassMethods) End Module ClassMethods def says 'test class method' test_commentable_classmethod end-end DEF Test_commentable_instance_method says 'test example methods' end-end ActiveRecord :: Base.send (include, commentable)  

and

What would it be to use it?

I like to start making modules, which, instead of the world, Can be included in any model; This feature can be reused more then I can include modules in ActiveRecord :: Base by creating a new base model class through a beginner or for my application. .

  # applications / concerns / my_module.rb module MyModule extension ActiveSupport :: anxiety module ClassMethods def has_some_new_fancy_feature (option = {}) ... end end end  
< P> Module is a form of multi-heritage, and sometimes add unnecessary complexity. Check that a decorator or service object is the most understandable first.

Now that I have a module, I can write an initiator to include it only in the ActiveRecord :: base:

  # Config / initializers / activerecord_extensions.rb ActiveRecord :: Base.send (includes, MyModule)  

or monkey-patch without (see):

  #app / model / base_model. RB class bismodel & lt; ActiveRecord :: Base self.abstract_class = Edit MyModule End  

In a big project several months down the road, I have assumed my model is better that every model is new As the base model class, the problem of directly adding the module to ActiveRecord :: Base is that it can interfere with third-party code that depends on ActiveRecord. It is not better for monkey-patches, when you do not have it, in this case, creating a new base class can be simple for a long time.


Comments

Popular posts from this blog

sqlite3 - UPDATE a table from the SELECT of another one -

c# - Showing a SelectedItem's Property -

javascript - Render HTML after each iteration in loop -