通过const_missing动态创建名称类

时间:2013-09-17 13:21:47

标签: ruby binding anonymous-class

我有这个模块:

module Api
  module ObjectMapper
    def self.const_missing const_name

      anon_class = Class.new do
        def self.foo
          puts self.class.name
        end
      end

      const_set const_name, anon_class
    end
  end
end

我希望能够在运行时使用可以使用foo调用的方法Api::ObjectMapper::User::foo来定义匿名类。该功能应该将User打印到屏幕上。我尝试的所有内容都会导致某种错误,或者该功能会将Class打印到屏幕上。

如何修复我的类和方法定义,以便self.class.name正确解析?

3 个答案:

答案 0 :(得分:1)

我找到了解决方案。由于您是在const_missing方法的范围内定义匿名类,因此您可以使用const_name,它是您正在定义的类的名称。我不确定这是否是最佳解决方案,但确实有效。你必须像这样重新定义你的课程:

  anon_class = Class.new do
    define_singleton_method(:foo) do
      puts const_name
    end
  end

答案 1 :(得分:1)

类的名称只是引用它的第一个常量。原始代码的唯一问题是您使用的是self.class.name而不是self.name

module Api
  module ObjectMapper
    def self.const_missing const_name
      self.const_set const_name, Class.new{
        def self.foo
          name.split('::').last
        end
      }
    end
  end
end

p Api::ObjectMapper::User,      #=> Api::ObjectMapper::User
  Api::ObjectMapper::User.name, #=> "Api::ObjectMapper::User"
  Api::ObjectMapper::User.foo   #=> "User"

定义类方法(类上的单例方法)时,self是类。因此,self.class始终为Class,其名称为"Class"


原始答案,返回“用户”而不是“Api :: ObjectMapper :: User”

一种方法(不比基于闭包的解决方案更好)是在类上使用实例变量:

module Api
  module ObjectMapper
    def self.const_missing const_name
      anon_class = Class.new do
        def self.foo
          puts @real_name
        end
      end
      anon_class.instance_variable_set(:@real_name,const_name)
      const_set const_name, anon_class
    end
  end
end

Api::ObjectMapper::User.foo
#=> User

一种替代的,更严格的语法:

def self.const_missing const_name
  const_set const_name, Class.new{
    def self.foo; puts @real_name end
  }.tap{ |c| c.instance_eval{ @real_name = const_name } }
end

def self.const_missing const_name
  const_set const_name, Class.new{
    def self.foo; puts @real_name end
  }.instance_eval{ @real_name = const_name; self }
end

答案 2 :(得分:-1)

您还可以将foo方法定义为类方法

def self.const_missing const_name
  anon_class = Class.new do
    def self.foo
      puts self.class.name
    end
  end
end
相关问题