Ruby:包含动态模块名称
发布时间:2020-12-16 21:43:48 所属栏目:百科 来源:网络整理
导读:我的Rails应用程序中有一种情况,我需要根据当前的运行时状态包含任意模块.该模块提供仅在特定条件为真时才需要的自定义应用程序代码.基本上,我从当前上下文中提取公司名称,并将其用作模块及其定义的文件名: p = self.user.company.subdomain + ".rb"if File
我的Rails应用程序中有一种情况,我需要根据当前的运行时状态包含任意模块.该模块提供仅在特定条件为真时才需要的自定义应用程序代码.基本上,我从当前上下文中提取公司名称,并将其用作模块及其定义的文件名:
p = self.user.company.subdomain + ".rb" if File.exists?(Rails.root + "lib/" + p) include self.class.const_get(self.user.company.subdomain.capitalize.to_sym) self.custom_add_url end 我的测试模块如下所示: module Companyx def custom_add_url puts "Calling custom_add_url" end end 现在在控制台中,这实际上工作正常.我可以拉一个用户并包含这样的模块: [1] pry(main)> c = Card.find_by_personal_url("username") [2] pry(main)> include c.class.const_get(c.user.company.subdomain.capitalize)=> Object [3] pry(main)> c.custom_add_url 调用custom_add_url 如果我尝试从我的模型中运行include行,我会得到 NoMethodError: undefined method `include' for #<Card:0x007f91f9094fb0> 任何人都可以建议为什么include语句可以在控制台上工作,但不能在我的模型代码中工作? 解决方法
Include是一个类的方法.
如果要在模型中调用它,则需要在其单例类的上下文中执行代码. p = self.user.company.subdomain + ".rb" if File.exists?(Rails.root + "lib/" + p) myself = self class_eval do include self.const_get(myself.user.company.subdomain.capitalize.to_sym) end self.custom_add_url 编辑: class<<自我不接受障碍; class_eval,因此它保留局部变量的状态.我修改了我的解决方案以使用它. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |