salida extraña al llamar al método de clase base desde el módulo extendido

What I want to achieve is something like below, i.e. calling a base class method from extended modules method:

class BaseClass
  def behavior
    puts 'base class behavior'
  end
end

module ChildModule
  def behavior
   super.behavior
   puts 'child module behavior'
  end
end

o = BaseClass.new
o.extend ChildModule
o.behavior

and it outputs as follows (with ruby 1.9.2p290 (2011-07-09 revision 32553) [x86_64-linux])

base class behavior
t.rb:9:in `behavior': undefined method `behavior' for nil:NilClass (NoMethodError)
       from t.rb:16:in `<main>'

My guess is that I can not use super, ya que super does not exist in the module. But it prints out that line from the super method, is that strange?

How do I achieve it what I want above?

Answer by @davidrac is working, however being more curious, would like to know, how can I get a handle to base class instance? Say for instance I added the following method to BaseClass

def behavior2
  puts 'base class behavior2'
end

and overrides it in ChildModule. Now from ChildModule behavior can I make a call to behavior2 of BaseModule?

preguntado el 31 de julio de 12 a las 10:07

1 Respuestas

Creo que la sintaxis correcta es:

module ChildModule
  def behavior
   super
   puts 'child module behavior'
  end
end

Respondido 31 Jul 12, 10:07

just being curious, modifying my question to know how I get handle to base class - Amol Pujarí

simply use MyClass.superclass. see here: ruby-doc.org/core-1.9.3/Class.html - davidrac

but MyClass is not a class but a module here - Amol Pujarí

Oh, now I see. A module may not inherit from anything. I don't see in your code any indication that BaseClass is the superclass of ChildModule - davidrac

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.