Question

The following prints Bar twice:

class Foo
  def foo
    p self.class # => prints Bar
  end
end

class Bar < Foo
  def foo
    p self.class # => prints Bar
    super
  end
end

b = Bar.new
b.foo

How do I get it to print

Bar
Foo

? i.e. I want to know what class each method is defined on.

Was it helpful?

Solution

To capture the context in which a method was originally defined, you can use define_method instead of def to get the appropriate closure. A simple example:

class Foo

  klass = self
  define_method(:foo){p klass}

end

class Bar < Foo

  def foo
    p self.class
    super
  end

end

b = Bar.new

b.foo

OTHER TIPS

You could change Foo#foo like so (provided there is just one subclass level):

class Foo
  def foo
    if self.class == Foo
      p self.class
    else
      p self.class.superclass
    end  
  end
end

class Bar < Foo
  def foo
    p self.class
    super
  end
end

Foo.new.foo
Foo
Bar.new.foo
Bar
Foo

You can use

 b.class.superclass   <= "Foo"

The problem you are having there is that self is the instance of Bar, b.

 b.class   <= always going to be Bar
 self.class   <= always going to be Bar if you are invoking Bar. 

You say that you are defining a method at runtime, and that you don't know the class name. I don't really know what you mean ... the way I would handle this would be something like

class Bar
  def initialize  
   puts 'In BAR class'  
  end  

  def foo
    p self.class.name # => prints Bar
  end
end

and then

Bar.class_eval do
   def brand_new_method
      # do something new
      p "Still in Bar, but this is dynamically added"
   end
end

Maybe you are talking about dynamically adding methods to classes higher in the inheritance chain ... to "Foo" in your example ... based on some conditional happening in an instance of "Bar". If that is the case, then why don't you use a single module to define your inherited methods:

module Foo
    def foo 
        p self.class
    end
end

and then use module_eval the same way as class_eval?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top