Is it possible to extend a class by using a string as a module ? - Ruby 2.7.1

不打扰是莪最后的温柔 提交于 2021-02-19 03:54:05

问题


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

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 :

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 ?

Thanks in advance !


回答1:


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

Where const_get can easily resolve simple module names like X and X::Y.

There's also the constantize method in ActiveSupport, bundled with Rails, which does something similar:

extend var.constantize


来源:https://stackoverflow.com/questions/62700655/is-it-possible-to-extend-a-class-by-using-a-string-as-a-module-ruby-2-7-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!