是否可以通过使用字符串作为模块来扩展类?-Ruby 2.7.1 [英] Is it possible to extend a class by using a string as a module ? - Ruby 2.7.1
问题描述
我正在FreeBSD 12.1上使用Ruby 2.7.1进行一些测试.我知道如何使用以下模块扩展类:
I am doing some tests with Ruby 2.7.1 on FreeBSD 12.1. I know how to extend a class with module with for instance this :
class Myclass
def mymethod
extend Mymodule
end
end
但是通过如下所示的方式可以获得相同的结果:
But is it possible to obtain the same result with something that looks like this :
class Myclass
def mymethod
var = "Mymodule"
extend var
end
end
如果我那样做,我当然会出错,因为extend指向的是字符串而不是模块.
If I do this like that, I off-course obtain an error, since extend is pointing to a string and not a module.
以下是一些说明-例如,在以下应用程序中会很有用:
Here are some explanations - it would be useful in the following application for instance :
想象一下,您有一个包含很多ruby脚本的文件夹,它们都是名称明显的模块.例如,abcd.rb将包含模块Abcd.因此,我创建了一个文件列表并将其保存在数组中.然后,我可以加载或要求此阵列中列出的所有这些文件.由于模块的名称是可预测的,因此我只需要对数组的索引执行一些.sub,.chop和.capitalize方法即可获得看起来像模块名称的可行结果.
Imagine you have a folder with a lots of ruby scripts, all of them are module with obvious name. For instance abcd.rb will contain the module Abcd. So I create a file list and save it in an array. Then I can load or require all these file listed in this array. Since the name of modules are predictable, I just have to do some .sub, .chop and .capitalize method to the indices of my array in order to obtain a viable result that looks just like the name of a module.
该想法是创建一种自动扩展所有这些模块的主类的方式.按照这种想法,添加到该文件夹中的所有模块都将自动加载并准备使用.
The idea would be to create a mean of extending my main class with all these modules automatically. In this idea, any modules added to the folder will be automatically loaded and ready for use.
但是,由于我的数组操作的结果不是纯"的,因此,模块名称,但字符串我卡在这里.
But since the result of my array operations are not "pure" modules names but String I got stuck right here.
那么,有什么方法可以做到这一点(也许我使用了错误的路径来做到这一点)还是不可能?
So, is there any way to achieve this (maybe I use a wrong path to do so) or is not possible ?
提前谢谢!
推荐答案
您不能扩展任意字符串"
,但可以将其转换为 module
首先:
You can't extend "arbitrary string"
, but you can convert that to a module
first:
class Myclass
def mymethod
var = "Mymodule"
extend self.class.const_get(var)
end
end
const_get
可以轻松解析简单的模块名称,例如 X
和 X :: Y
.
Where const_get
can easily resolve simple module names like X
and X::Y
.
ActiveSupport中还提供了 constantize
方法,该方法与Rails捆绑在一起,其作用类似:
There's also the constantize
method in ActiveSupport, bundled with Rails, which does something similar:
extend var.constantize
这篇关于是否可以通过使用字符串作为模块来扩展类?-Ruby 2.7.1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!