Inheritance class changes method class

The following pictures Bartwice:

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 print it?

Bar
Foo

? that is, I want to know in which class each method is defined.

+4
source share
3 answers

To capture the context in which the method was originally set, you can use define_methodinstead defto get the corresponding 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
+3
source

You can change it Foo#foothis way (provided that there is only one level of the subclass):

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
0
source

 b.class.superclass   <= "Foo"

, , , self Bar, b.

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

, . , ... , , -

class Bar
  def initialize  
   puts 'In BAR class'  
  end  

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

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

Perhaps you are talking about dynamically adding methods to the classes above in the inheritance chain ... to "Foo" in your example ... based on some conditional event in the Bar instance. If so, then why not use a single module to define your inherited methods:

module Foo
    def foo 
        p self.class
    end
end

and then use module_eval just like class_eval?

-1
source

Source: https://habr.com/ru/post/1539664/


All Articles