How do I alias_method with ActiveSupport :: Concern?

I'm trying to run my own archiving on rails, but it's hard for me to figure out how to use the old destroy method before overriding it. Below I would like to do this, but I get a NoMethodError because destroy not defined before in the module. It works as I would expect if I put it in the InstanceMethods module, but it seems to be out of date. Should I just process it using the vanilla module or is there a way to do this using ActiveSupport::Concern ?

 module Trashable extend ActiveSupport::Concern included do default_scope where(deleted_at: nil) end module ClassMethods def deleted self.unscoped.where(self.arel_table[:deleted_at].not_eq(nil)) end end alias_method :destroy!, :destroy def destroy run_callbacks(:destroy) do update_column(:deleted_at, Time.now) end end end 
+4
source share
1 answer

You mix a couple of things.

1 - destroy doesn’t really exist in the class where you turn on your module before you turn on your module.

The long story is that the destroy method is probably generated and included in your ORM gem.

You can use ruby ​​2+ prepend to make sure your module appears after all the methods.

2 - You can use the vanilla module or ActiveSupport::Concern while you get what you want and know what you are doing.

The ActiveSupport::Concern point is primarily for managing module hierarchies. If you have one level, I see no reason to use it. I think mixing prepend with ActiveSupport::Concern not a good idea.

(And after all, ActiveSupport::Concern is just vanilla modules at the end.)

3 - The recommended way to override a method while keeping the old one is to use alias_method_chain .

You will have the destroy_without_archive method available, which will be the old way to execute it (before you flip it).

0
source

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


All Articles