上篇有个标准的定义动态类变量
class MyClass
class << self
attr_accessor :my_constant
end
def my_method
self.class.my_constant = "blah"
end
end
p MyClass.my_constant #=> nil
MyClass.new.my_method
p MyClass.my_constant #=> "blah"
如果类也动态定义,那么子类和module怎么定义进去的
dynamic_name = "TestEval2"
Object.const_set(dynamic_name, Class.new{def method1() 42 end }})
dummy2 = eval("#{dynamic_name}")
puts "dummy2: #{dummy2}"
dynamic_name = "SubTestEval2"
SubModule.const_set(dynamic_name, Class.new(TestEval2){def method1() 43 end })
dummy3 = eval("#{dynamic_name}")
puts "dummy3: #{dummy3}"
判断动态类是否存在
def class_exists?(class_name)
eval("defined?(#{class_name}) && #{class_name}.is_a?(Class)") == true
end
class_name = "Blorp"
class_exists?(class_name)
=> false
class_name = "String"
class_exists?(class_name)
=> true
define_method定义的方法参数放到哪?
define_method(:say_hi) { |other| puts "Hi, " + other }