0

我有一个模块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)有人可以证明我错了吗?

4

1 回答 1

0

You can make all these methods class methods and do the following:

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

Not sure if that would work for you.

于 2012-08-26T14:46:29.437 回答