patrick
patrick

Reputation: 9742

Is there a way to get a reference to a module from within a method?

say I have:

module A
  def hello
    puts self
  end
end

class B
  include A
end

B.new.hello

I get: #<B:0x007fa10b8c29f0>

... Is there a way I can get a reference to the module so that I could do something access a "class method" from within a module, and not actually have that class method get included into the class including the module...

module A
  def self.not_included
    # something
  end

  def hello
    puts self.class.not_included
  end
end

In other words, when I class B includes A, I want B.new.methods to only contain the method "hello".

Upvotes: 1

Views: 62

Answers (2)

denis-bu
denis-bu

Reputation: 3446

you can use trick to extend class with class methods like this:

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

This would of course pollute self methods of class B, but live intact instance methods of B's objects. Thus you can use this.class.not_included within instance method of B.

Upvotes: 1

konsolebox
konsolebox

Reputation: 75488

Why not just refer the module directly:

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

Output:

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__]

Of course you can also pass the instance:

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

  def hello
    puts A.not_included(self)
  end
end

Upvotes: 1

Related Questions