7

在运行时创建一个类如下:

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"
4

2 回答 2

15

比你想象的要容易:)

Company.const_set "Employee", klass

当你ObjectObject. 但是你可以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"
于 2012-06-24T11:05:36.740 回答
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]
于 2012-06-24T11:05:33.970 回答