模块何时包含在在 Rails 中运行的 Ruby 类中?
我正在尝试编写一个方法来告诉我包含特定模块的每个类。它看起来像这样 -
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当定义类时执行 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:
This will build the list as classes include the module.