Fun with Ruby blocks, modules, class inheritance, and “super”

Posted by admin on April 14, 2008

The situation: A class, it’s descendant, and a module included in the parent class all have a method of the same name. Calling super from the child’s method causes a call to the parent class and not the module…

module Something
  def foo(&block)
    puts "Hello Module,"
    yield
    puts "Goodbye Module... it was nice knowing you. "
  end
end

class ParentFun
  include Something

  def foo(&block)
    puts "Hello Parent,"
    yield
    puts "Goodbye Parent.. it was nice knowing you"
  end
end

class ChildFun < ParentFun
  def foo
    super do
      puts "I am a Child."
    end
  end
end

ChildFun.new.foo #=>
# Hello Parent,
# I am a Child.
# Goodbye Parent.. it was nice knowing you

Now put the module include in the Child class instead of Parent.

module Something
  def foo(&block)
    puts "Hello Module,"
    yield
    puts "Goodbye Module... it was nice knowing you. "
  end
end

class ParentFun
  def foo(&block)
    puts "Hello Parent,"
    yield
    puts "Goodbye Parent.. it was nice knowing you"
  end
end

class ChildFun < ParentFun
  include Something

  def foo
    super do
      puts "I am a Child."
    end
  end
end

ChildFun.new.foo #=>
# Hello Module,
# I am a Child.
# Goodbye Module... it was nice knowing you.

Interesting.

Trackbacks

Use this link to trackback from your own site.

Comments

Leave a response

Comments