有没有办法从方法中获取模块的引用?

时间:2014-08-07 08:07:07

标签: ruby

说我有:

module A
  def hello
    puts self
  end
end

class B
  include A
end

B.new.hello

我得到:#< B:0x007fa10b8c29f0>

...有没有办法可以获得对模块的引用,这样我就可以做一些访问"类方法"从一个模块中,并没有实际将该类方法包含在包含模块的类中......

module A
  def self.not_included
    # something
  end

  def hello
    puts self.class.not_included
  end
end

换句话说,当我的B类包含A时,我希望B.new.methods只包含方法" hello"。

2 个答案:

答案 0 :(得分:1)

为什么不直接参考模块:

module A
  def self.not_included
    :not_included
  end

  def hello
    puts A.not_included
  end
end

class B
  include A
end

b = B.new
b.hello
puts b.methods.inspect

输出:

not_included    
[:hello, :nil?, :===, :=~, :!~, :eql?, :hash, :<=>, :class, :singleton_class, :clone, :dup, :taint, :tainted?, :untaint, :untrust, :untrusted?, :trust, :freeze, :frozen?, :to_s, :inspect, :methods, :singleton_methods, :protected_methods, :private_methods, :public_methods, :instance_variables, :instance_variable_get, :instance_variable_set, :instance_variable_defined?, :remove_instance_variable, :instance_of?, :kind_of?, :is_a?, :tap, :send, :public_send, :respond_to?, :extend, :display, :method, :public_method, :singleton_method, :define_singleton_method, :object_id, :to_enum, :enum_for, :==, :equal?, :!, :!=, :instance_eval, :instance_exec, :__send__, :__id__]

当然你也可以传递实例:

module A
  def self.not_included(instance)
    "not_included got #{instance}"
  end

  def hello
    puts A.not_included(self)
  end
end

答案 1 :(得分:0)

你可以使用技巧来扩展类,如下所示:

module My
  def self.included base
    base.extend ClassMethods
  end

  module ClassMethods
    def not_included
      #...
    end
  end

  def included_method; end
end

class B
  include My

  def instance_method; self.class.not_included end
end

B.new.included_method
B.new.instance_method

这当然会污染class B的自我方法,但是对B的对象实时完整的实例方法。因此,您可以在B的实例方法中使用this.class.not_included