Rails: module callbacks

I am trying to do this:

application / models / my_model.rb:

class MyModel <  ActiveRecord::Base
  include MyModule
  ...
end

Library / my_module.rb:

module MyModule
  before_destroy :my_func    #!

  def my_func
    ...
  end
end

but I get an error:

undefined method `before_destroy' for MyModule:Module

How can I fix it.

I'm also new to ruby. What type has these "attributes": before_destroy, validates, has_many? Are they variables or methods or what? Thanks

+5
source share
3 answers

before_destroy, validatesetc. are not attributes or anything like that. These are method calls.

In ruby, the class body is all executable code, which means that each line of the class body is executed by the interpreter in the same way as the body of the method.

before_destroy :my_func - ruby. before_destroy, :my_func . ( ), .

, , , ,

module MyModule
  before_destroy :my_func    #!

  def my_func
    ...
  end
end

before_destroy . , , , , . Module#included:

module MyModule
  module InstanceMethods
    def my_func
      ...
    end
  end

  def self.included(base)
    base.send :include, InstanceMethods
    base.before_destroy :my_func
  end
end
+14

lib/my_module.rb :

  class MyInheritedClass <  ActiveRecord::Base
    before_destroy :my_func
    def my_func
       ...
    end
  end

/models/my _model.rb :

class MyModel < MyInheritedClass
  ...
end

, , before_destroy. , , ActiveRecord:: Base, , . ActiveRecord:: Base.

0

u , before_destroy MyModule MyModel

before_destroy , ActiveRecord:: Base,

, =)

0

All Articles