I'm learning Ruby and working on my first real project. The program will receive a data structure and needs to reproduce the information contained that structure in various text formats. All of the different output types rely on the same set underlying attributes (about 40 of them) and the same set of common functions (about 10 of them); but they differ in how they render the information as text.
My initial inclination was to design this using inheritance, as illustrated in the example below. However:
- I'm not certain how to do this (see
code comments in
Foo.produce_output
). - I'm wondering whether I'm on the wrong track altogether by using inheritance rather than something else -- a mixin?
Ideally, users of the project would not have to concern themselves with all of the format-specific classes (FooFormatA
, FooFormatB
, etc.). Instead, they would deal only with Foo
.
Any advice would be appreciated.
class Foo
attr_accessor :output_types # Many other common attributes.
def produce_output
# Take a Foo object and invoke the
# appropriate produce_output method for
# each of the output types.
end
# Various other common methods.
end
class FooFormatA < Foo
def produce_output
puts "FooA"
end
end
class FooFormatB < Foo
def produce_output
puts "FooB"
end
end
class FooFormatC < Foo
def produce_output
puts "FooC"
end
end
# Example use case.
f = Foo.new
f.output_types = ['A', 'C']
f.produce_output