标记模块中的方法以供混合类参考

时间:2012-08-25 23:07:13

标签: ruby module metaprogramming class-method instance-methods

我有一个模块M我希望将特定方法标记为“特殊”,这样在这个模块中混合的类可以检查给定的方法名称是否特殊。这就是我尝试过的:

module M
  def specials
    @specials ||= {}
  end

  def self.special name
    specials[name] = true
  end

  def is_special? name
    specials[name]
  end

  def meth1
    ...
  end
  special :meth1
end

class C
  include M

  def check name
    is_special? name
  end
end

当然这不起作用,因为我无法从类方法self.special调用实例方法。我怀疑如果我想保持能够在模块中的所需方法下面调用special :<name>的功能,我别无选择,只能使用类变量(例如@@specials)有人可能证明我错了?

1 个答案:

答案 0 :(得分:0)

您可以将所有这些方法设为类方法并执行以下操作:

module M
  def self.specials
    @specials ||= {}
  end

  def self.special name
    self.specials[name] = true
  end

  def self.is_special? name
    self.specials[name]
  end

  def meth1
    'foo'
  end

  def meth2
    'bar'
  end

  special :meth1
end

class C
  include M

  def check name
    M.is_special? name
  end
end

p C.new.check(:meth1)
#=> true
p C.new.check(:meth2)
#=> nil

不确定这是否适合你。