ruby - 如何动态扩展类上的模块?
问题描述
我目前有两个类,每个类扩展一个不同的模块:
class Example1
def initialize
extend TopModule:SubModule1
end
end
class Example2
def initialize
extend TopModule:SubModule2
end
end
是否可以创建一个类然后在对象级别扩展模块,而不是让两个类都扩展自己的模块?
我已经添加了模块的名称并将其传递给对象的构造函数,但抱怨代码。
class Example
def initialize (module)
self.send("extend TopModule::#{module}"
end
end
object = Example.new('Submodule1')
NoMethodError:
undefined method `extend TopModule::SubModule1' for #<Example:0x00000000057c8198>
总体问题:假设我有 N 个对象(它们都应该来自同一个类,但每个对象都必须有自己的模块)。拥有这种能力的最佳方法是什么?
解决方案
更新答案!
module TopModule
module SubModule1
def hello
puts "Hello from #1"
end
end
end
module TopModule
module SubModule2
def hello
puts "Hello from #2"
end
end
end
class Example
def initialize(mod)
extend TopModule.const_get(mod)
end
end
Example.new("SubModule1").hello
# => Hello from #1
Example.new("SubModule2").hello
# => Hello from #2
推荐阅读
- javascript - 另一种保存流媒体的方法
- xamarin - Xamarin HybridWebView 在 EvaluateJavaScript 抛出异常
- python - Pandas - 处理日期格式转换的更好方法
- r - 此版本的 ChromeDriver 仅支持 Chrome 版本 84
- excel - 自动添加列和公式然后向下填充
- oracle - SQL*Plus 语法不通过 SQL Developer 中的 LDAP 连接
- c# - Blazor INPUT 控制 e.Key 未定义
- c# - 依赖本地 C# 项目
- powerbi - Power BI 中的动态数据库使用
- neo4j - “with”关键字改变结果