您可以在 Rails 模块中包含 before/after 过滤器吗? [英] Can you include before/after filters in a Rails Module?

查看:38
本文介绍了您可以在 Rails 模块中包含 before/after 过滤器吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为两个模型添加一个方法,所以我制作了一个这样的模块并将其包含在两个模型中.

I wanted to add a method to two models, so I made a module like this and included it in both models.

module UserReputation
  def check_something
    ...
  end
end

效果很好.然后我想在所有这些模型上将该方法称为 :after_create .如果我手动将它添加到所有模型中,它会起作用,但我想变得聪明并将它包含在这样的模块中:

That worked fine. I then wanted to have that method called as an :after_create on all those models. It works if I add it manually to all the models, but I wanted to be smart and include it in the module like this:

module UserReputation
  after_create :check_something
  def check_something
    ...
  end
end

但这行不通.有什么方法可以完成此操作并同时完成 after_create 吗?

But this doesn't work. Is there any way to accomplish this and DRY up the after_create as well?

推荐答案

尝试 self.included,在模块混入类base时调用:

Try self.included, which is called when the module is mixed into the class base:

module UserReputation
  def self.included(base)
    base.after_create :check_something
  end
end

这篇关于您可以在 Rails 模块中包含 before/after 过滤器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆