简体   繁体   English

Rails:定义要覆盖的 scope 的正确方法

[英]Rails: correct way to define a scope to be overridden

I'm using the gem discarded which adds a scope with_discarded on every model on which it is loaded on.我正在使用被丢弃的 gem,它在加载它的每个 model 上添加了一个 scope with_discarded。 To write some code that works with any model I added with_discarded scope (via a class method) on all models in application_record that does nothing so that then it will get overridden in those models which include the module from the discarded gem.为了编写一些适用于任何 model 的代码,我在 application_record 中的所有模型上添加了 with_discarded scope (通过 class 方法),这些模型不执行任何操作,因此这些模型中的模块将被丢弃的 gem 覆盖

However, rails now produces a warning: Creating scope:with_discarded. Overwriting existing method User.with_discarded但是,rails 现在会产生警告: Creating scope:with_discarded. Overwriting existing method User.with_discarded Creating scope:with_discarded. Overwriting existing method User.with_discarded every time I load a class that overwrites the base method.每次我加载覆盖基本方法的 class 时,都会Creating scope:with_discarded. Overwriting existing method User.with_discarded For completeness that's implemented just as:为了完整性,它的实现方式如下:

  def self.with_discarded 
    all
  end

Now everything seems to be working fine, but I'm wondering what the correct way to do this would be and why I'm being warned.现在一切似乎都运行良好,但我想知道正确的方法是什么以及为什么我被警告。 Am I supposed to define it as a scope rather than a class method (EDIT: tried it still get the warning)?我是否应该将其定义为 scope 而不是 class 方法(编辑:尝试过仍会收到警告)? Alternatively, is there a way to just filter this warning out of all my logs without loading a gem like Semantic Logger.或者,有没有办法从我的所有日​​志中过滤掉这个警告,而不加载像 Semantic Logger 这样的 gem。 Problem is that this warning shows up every time my GoodJob Scheduler runs and is polluting my logs.问题是每次我的 GoodJob Scheduler 运行并污染我的日志时都会出现此警告。

So I followed @tadman's suggestion and just implemented a new method as follows所以我按照@tadman的建议,刚刚实现了一个新方法如下

  def self.include_discarded
    respond_to?(:with_discarded) ? with_discarded : all
  end

This doesn't quite let me overload the original with_discarded scope in the sense that I had to switch all the uses to include_discarded but it has the same effect.这并没有让我重载原始的 with_discarded scope,因为我必须将所有用途切换到 include_discarded 但它具有相同的效果。 You could try and give the method the same name via metaprogramming but then you'll need a good way to run code in every subclass of ApplicationRecord.您可以尝试通过元编程为该方法赋予相同的名称,但是您需要一种在 ApplicationRecord 的每个子类中运行代码的好方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM