Ruby Custom Super Initialization
-
27-09-2019 - |
Question
Here is my situation:
XMLRPC::Client
has a proxy constructor,new3
, that takes a hash of options. It takes out the individual values to then delegate the construction to the default initializer,initialize
- I am deriving from
XMLRPC::Client
. I want a class that isXMLRPC::Client
but with some added functionality. - I want to be able to instantiate this derived class using a hash of options as well. This means that in my derived class' initializer, I have to somehow instantiate
super
using thenew3
proxy constructor.
My Question Is if this is possible. If not, then is the only way to solve this is to practically 'copy and paste' the code within the XMLRPC::Client.new3
method into my derived class' constructor?
The reason I'm asking this is simply to see if there is a way of solving this problem, since there is this recurring theme of DRY (Don't Repeat Yourself) within the Ruby community. But of course, if this is the only way, it wont kill me.
Solution
I am only posting an answer supplement the other answers by showing you how XMLRPC's code is written
def new3(hash={})
# convert all keys into lowercase strings
h = {}
hash.each { |k,v| h[k.to_s.downcase] = v }
self.new(h['host'], h['path'], h['port'], h['proxy_host'], h['proxy_port'], h['user'], h['password'],
h['use_ssl'], h['timeout'])
end
http://www.ensta.fr/~diam/ruby/online/ruby-doc-stdlib/libdoc/xmlrpc/rdoc/classes/XMLRPC/Client.html
OTHER TIPS
Make a new class method in your derived class (much like they did to make new3
in the first place):
class MyDerived < XMLRPC::Client
def self.new3(hashoptions)
client = XMLRPC::Client.new3(hashoptions)
# Do further initialisation here.
end
end
myone = MyDerived.new3(:abc => 123, ...)
super
only works in initialize
(and only changes the parameters to the superclass's initialize
), so it doesn't apply here.
You should probably be able to call new3
on you subclass
class MyClient < XMLRPC::Client
end
MyClient.new3({})
Or overwrite it if you need to do extra stuff:
class MyClient < XMLRPC::Client
def self.new3(args)
client = super(args)
# do some more stuff
client
end
end
MyClient.new3({})