何时在rails中运行的Ruby类中包含模块? [英] When are modules included in a Ruby class running in rails?

查看:73
本文介绍了何时在rails中运行的Ruby类中包含模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

其中"Rateable"是我要在多个模型中包括的模块.

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

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

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?

推荐答案

在定义类时执行include语句时,将包括它们.首次使用时,Rails会自动加载模块/类.另外,您可以尝试执行以下操作:

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.

这篇关于何时在rails中运行的Ruby类中包含模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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