I would like to create an abstract class which will create concrete instances depending on initialization parameter. Example:
class SomethingGeneric
def self.new(type, arg)
class_name = "#{type.capitalize}Something"
if obj.const_defined?(class_name)
a_class = obj.const_get(class_name)
else
raise ArgumentError, "Concrete something '#{type}' was not found"
end
obj = a_class.new(arg)
return obj
end
end # class
Then I would like to have FooSomething < SomethingGeneric, BarSomething < SomethingGeneric and more. Then when I do:
obj = SomethingGeneric.new("foo", arg)
I would get FooSomething instance.
My problem here is the "new" method. I have defined SomethingGeneric.new, however FooSomething and BarSomething are subclasses of SomethingGeneric therefore they inherit the "new" method which is called with wrong arguments here:
obj = a_class.new(arg)
One of the solution would be to use another name for the factory method 'new'. However I would like to stick with convenience and keep the abstract superclass factory method named 'new'.
What is the cleanest correct way to solve this problem?
your new method should take one param: *args
you'll want to grab the first item out of the array as your type var, and then remove that item from the array so you can pass the rest of the args down to the next new call.
Array#shift will give you the first item and then remove it.