我正在尝试创建一个类型非常灵活的 Ruby 类,并且希望可以根据其初始化的值从许多其他类继承属性:
class Test
def initialize(type,etc)
case type
when "stringio"
inherit_from_stringio_with_data(etc)
when "list"
inherit_from_enumerable_with_data(etc)
# and so on
end
end
end
Test.new("list").each do |item|
p item
end
s = Test.new("stringio")
s.seek(3)
puts s.read(2)
我知道 - 或者更确切地说已经读过 - mixin 的强大功能,但据我所知,这并没有完全正确地布局。有没有人有任何想法,或者我正在尝试以其他方式最好地实现的东西(例如 @content
,其中包含 etc
作为 StringIO
,可枚举
等)。
谢谢!
最佳答案
module Stringy
def foo
puts "I am a stringy"
end
end
module Inty
def bar
puts "I am inty"
end
end
class Test
def initialize(mod_type)
self.extend(mod_type)
end
end
test = Test.new(Stringy)
关于ruby - Ruby 中的动态继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1679615/