Greetings!
A friend of mine has recently started using Ruby, and has run into a
little problem. He is trying to create different objects depending on
the contents of a string. His intuition is to use factory design for
this, and he'd like to know if there is a Ruby Way to do this.
Below is his original e-mail.
Regards...
-CWS
----8<----
Hello, I'm wondering if anyone can suggest a good Ruby idiom for the
following problem. I'm pretty new to Ruby and am migrating from
statically-typed languages like Java and C++.
I have a string representation of some data that I want to read from an input
source and load into a file. Based on what this input is, I want to create a
subclass.
The concrete example is that I have a number of "events" in a log file that I
want to be able to create based on the input I read. There are three kinds
of events: a Phase, an Interruption, and a Defect. Each one of them has a
beginning time, a duration, and a comment.
Phases can contain Interruptions and Defects. Defects can contain
Interruptions and other Defects.
In any case, I have an identifier on my log file that looks like "2005-01-04
23:34:12 begin_phase". If I see this, I want to create a "Phase" object. If
it says "2005-01-04 23:52:16 begin_interruption", then I want to create an
interruption instead.
My intuition is that this is a typical Factory Design Pattern, so I would
create a Ruby class method that creates the appropriate type based on the
results of the string and returns it. However, someone familiar with Ruby
told me that Ruby's dynamic typing and duck typing is such that this kind of
solution "feels incorrect".
Does anyone have suggestions as to what I can do? Thanks!
-- -- Irwin (ihkwan at gmail.com)