Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inherit initialize() method in ruby? [closed]

Tags:

ruby

I still can't figure out how to make a subclass constructor follow its parent...
example:

require 'mechanize'

class Scraper
    attr_accessor :agent

    def initialize 
    # I dont know if using instance variable is the right thing to do
    @agent = Mechanize.new 
    end
end

class ScraperA < Scraper
end

I want to make ScraperA follow its parent constructor behaviour,
that is instantiate a Mechanize object without me retyping Mechanize.new in ScraperA initialize() method. Is this possible ?

Just want to follow DRY principle but ruby makes it hard for me ???
Hope not, maybe it's just my ignorance. Looking forward for simple solution,Tnx.

Edit:
it turns out that I had empty initialize() method in ScraperA, which override the default initialize(). So yeah the example is working, because no empty initialize method there. Sorry for my stupidity. Tnx.

like image 209
mhd Avatar asked Jul 12 '10 15:07

mhd


2 Answers

Umm... eh? Yes it does... Check this out:

class A
  def initialize
    @a = "foo"
  end
end

class B < A
  def to_s
    @a
  end
end

puts B.new
# "foo" is printed

This works because initialize is inherited, just like any other method. If you override it by having a new sub-initialize, it stops working. Then you can explicitly use super to call the parent's initialize.

like image 154
Amadan Avatar answered Nov 14 '22 14:11

Amadan


This should work...

class ScraperA < Scraper

  def initialize
    super

    # do other stuff here if necessary
  end

end

...if you want to have other logic for the subclass. As the comments say if the constructor is exactly the same as for the parent class your original code should work just fine.

like image 35
DanSingerman Avatar answered Nov 14 '22 14:11

DanSingerman