it-swarm.cn

是否可以在模块中定义'before_save'回调?

是否可以在模块中定义before_save回调?这样的类是这样的:

class Model
  include MongoMapper::Document
  include MyModule
end

和这样的模块:

module MyModule
  before_save :do_something

  def do_something
    #do whatever
  end  
end 

do_something将在保存任何Model对象之前被调用?我试过这样但得到undefined method 'before_save' for MyModule:Module

抱歉,如果这很简单 - 我是Ruby和Rails的新手。

57
Russell

在Ruby on Rails <3(没有Rails功能,只有Ruby)

module MyModule
  def self.included(base)
    base.class_eval do
      before_save :do_something
    end
  end

  def do_something
    #do whatever
  end
end

在Ruby on Rails中> = 3(使用Rails Concern特性)

module MyModule
  extend ActiveSupport::Concern

  included do
    before_save :do_something
  end

  def do_something
    #do whatever
  end
end
106
Simone Carletti

模块的included方法可能就是您所需要的。

http://www.Ruby-doc.org/core-2.1.2/Module.html#method-i-included

4
jimworm

您可以使用ActiveSupport :: Concern执行此操作(实际上没有它,但它更清晰,更首选)

require 'active_support/concern'

module MyModule
  extend ActiveSupport::Concern

  included do
    # relations, callbacks, validations, scopes and others...
  end

  # instance methods

  module ClassMethods
    # class methods
  end
end
0
user1136228