Topic: Calling a parent class' method

I'm looking for a Ruby equivalent for Java's super reference keyword.

class Parent
  def something
  end
end

class Child
  def something
    # overwritten method
  end

  def something_else
    _reference_to_parent_.something # here I want to call the parent's
                                    # implementation, not the locally
                                    # overwritten one
  end
end


In something_else I want to call the parent's implementation of the method something, not the (overwritten) method in the same class.

In Java I would do...

class Child
  ..
  def something_else
    super.something
  end
end

Super in Ruby has a different semantics, calling the same method in super.

Any ideas ?

Re: Calling a parent class' method

The "super" keyword in ruby behaves a little differently than other languages. Instead of returning an instance of the superclass, it calls the superclass's method of the method you're currently in. So:

def foo
  super
end

Is the same as

void foo()
{
  super.foo()
}

This means what you want to do isn't really possible without some ugly hackery.

Instead, you should work around this by refactoring and moving methods around. In this case you could give "something" a different name in the subclass so a call to "something" will drop to the superclass. You'll probably end up with a better design this way too.

Railscasts - Free Ruby on Rails Screencasts

Re: Calling a parent class' method

Hmm, that's strange. I think that this is a serious limitation of the Ruby language, but may be it's just my bad C++/Java-inheritance that drives me into breaking OO.

I faced this problem in my LabeledFormHelper class, where the methods for text_field, ... are overwritten so that the generated HTML output includes a label and the widget itself, encapsulated in a paragraph.

However in some LabeledFormHelper methods I still need the original behaviour of FormHelper (rendering the text_field without a label and without a paragraph). In theses cases accessing the parent implementation would be handy.

In my sitution I can circumvent the problem by renaming some methods, but IMHO this is an ungly hack.

Re: Calling a parent class' method

There's also alias_method.

alias_method :text_field_without_label, :text_field

def text_field
  # with label
end


Now you have the old method you can access with text_field_without_label. You may want to use alias_method_chain for this as well. I forgot the exact syntax but it might be this:

alias_method_chain :text_field, :label

def text_field_with_label
  # with label
end

Railscasts - Free Ruby on Rails Screencasts