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.
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With