本文介绍了是否可以在模块中定义“before_save"回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

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

Is it possible to define a before_save callback in a module? Such that with a class like this:

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.

do_something will be called before any Model objects are saved? I've tried it like this but get undefined method 'before_save' for MyModule:Module.

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

Apologies if it's something simple - I'm new to Ruby and to Rails.

推荐答案

在 Ruby on Rails 中

3(没有Rails特性,只有Ruby)

In Ruby on Rails < 3 (without Rails features, only 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 功能)

In Ruby on Rails >= 3 (with Rails Concern feature)

module MyModule
  extend ActiveSupport::Concern

  included do
    before_save :do_something
  end

  def do_something
    #do whatever
  end
end

这篇关于是否可以在模块中定义“before_save"回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 03:06