模块何时包含在在 Rails 中运行的 Ruby 类中?

发布于 2024-09-15 08:53:23 字数 456 浏览 5 评论 0原文

我正在尝试编写一个方法来告诉我包含特定模块的每个类。它看起来像这样 -

def Rating.rateable_objects
  rateable_objects = []
  ObjectSpace.each_object(Class) do |c|
    next unless c.include? Rateable
    rateable_objects << c
  end
  rateable_objects
end

其中“Rateable”是我包含在多个模型中的模块。

我发现,如果我在启动 Rails 控制台或运行服务器后立即调用该方法,该方法将返回 [] 。但是,如果我首先实例化其中一个消费模型的实例,它将在结果中返回该模型。

那么什么时候包含模块呢?我猜这个过程比他的应用程序启动的时间要晚。如果我无法在流程早期以这种方式获取此信息,是否有办法实现此目的?

I'm trying to write a method that tells me every class that includes a particular Module. It looks like this -

def Rating.rateable_objects
  rateable_objects = []
  ObjectSpace.each_object(Class) do |c|
    next unless c.include? Rateable
    rateable_objects << c
  end
  rateable_objects
end

Where "Rateable" is my module that I'm including in several models.

What i'm finding is that this method return [] if i call it immediately after booting rails console or running the server. But if i first instantiate an instance of one of the consuming models it will return that model in the result.

So when do modules get included? I'm guessing later in the process than when he app starts up. If i can't get this information this way early in the process, is there anyway to accomplish this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

心凉 2024-09-22 08:53:23

当定义类时执行 include 语句时,它们就会被包含在内。当您第一次使用模块/类时,Rails 会自动加载它们。另外,您可以尝试这样的操作:

module Rateable
  @rateable_object = []
  def self.included(klass)
    @rateable_objects << klass
  end
  def rateable_objects
    @rateable_objects
  end
end

这将构建列表,因为类包含模块。

They are included when the include statement is executed when the class is defined. Rails autoloads modules/classes when you first use them. Also, you might try something like this:

module Rateable
  @rateable_object = []
  def self.included(klass)
    @rateable_objects << klass
  end
  def rateable_objects
    @rateable_objects
  end
end

This will build the list as classes include the module.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文