在运行时创建类按如下方式完成:
klass = Class.new superclass, &block
Object.const_set class_name, klass
示例:
class Person
def name
"Jon"
end
end
klass = Class.new Person do
def name
"#{super} Doe"
end
end
Object.const_set "Employee", klass
puts Employee.new.name # prints "Jon Doe"
现在,假设您有一个名为Company的模块:
module Company
end
如何在Company模块/命名空间中创建Employee类在运行时,以便以下结果产生相同的结果?
puts Company::Employee.new.name # prints "Jon Doe"
答案 0 :(得分:15)
比你想象的容易:)
Company.const_set "Employee", klass
当您在Object
上设置内容时,它会变得全局化,因为一切都是Object
。但是你可以对每个类/模块const_set
。请记住,模块/类只是常量。因此,Company::Employee
是常量Employee
中的常量Company
。这很简单:)
完整代码:
class Person
def name
"Jon"
end
end
klass = Class.new Person do
def name
"#{super} Doe"
end
end
module Company
end
Company.const_set "Employee", klass
Company::Employee.new.name # => "Jon Doe"
答案 1 :(得分:2)
你已经拥有了所有必要的部分:
class Person
def name
"Jon"
end
end
klass = Class.new Person do
def name
"#{super} Doe"
end
end
module Company
end
Company.const_set "Employee", klass
puts Company::Employee.new.name # prints "Jon Doe"
Company.constants.grep(/Emp/)
#=> [:Employee]