D
Daniel Berger
Hi all,
I'm trying to setup an abstract base class as a factory for its
subclasses. The below code fails, as it always returns an instance of
Foo::Bar instead of one of its subclasses.
module Foo
class Bar
def initialize(arg)
return if self.class != Foo::Bar
case arg.downcase
when 'baz'
return Baz.new(arg)
when 'zap'
return Zap.new(arg)
end
end
end
class Baz < Bar
end
class Zap < Bar
end
end
fb = Foo::Bar.new('baz')
p fb # Returns Foo::Bar, but I want Foo::Baz
Perhaps my whole approach is wrong. What is the proper way to achieve
what I'm after (without resorting to making Bar a module)?
Thanks,
Dan
I'm trying to setup an abstract base class as a factory for its
subclasses. The below code fails, as it always returns an instance of
Foo::Bar instead of one of its subclasses.
module Foo
class Bar
def initialize(arg)
return if self.class != Foo::Bar
case arg.downcase
when 'baz'
return Baz.new(arg)
when 'zap'
return Zap.new(arg)
end
end
end
class Baz < Bar
end
class Zap < Bar
end
end
fb = Foo::Bar.new('baz')
p fb # Returns Foo::Bar, but I want Foo::Baz
Perhaps my whole approach is wrong. What is the proper way to achieve
what I'm after (without resorting to making Bar a module)?
Thanks,
Dan