I have the following CSV entries:
2014-05-19 02:33:36,590,MGW,5147014,3056260212,ONNET,IN,CALL,95
2014-05-19 02:33:37,139,MGW,8827533,923049586878,ONNET,IN,N
Using different classes to carry out the same task with different algorithms is the Strategy pattern, but the Gang of Four's original definition of the Strategy pattern doesn't deal with selecting strategies. That comes up all the time and I'd handle it like this:
Write a class -- let's call it a Creator
-- for each type of CSV line with a method create!
that checks to see if the line matches the class's type, parses the line (maybe a superclass will be helpful here), saves the entry in the database and returns it. If the Creator
doesn't match the line, create!
just returns nil.
Then, in the "conveyer":
lines.each do |line|
[RedirectedCreator, CallCreator, AlertCreator].each |creator|
if creator.new.create! line
break
end
end
end
If the process of saving the entry to the database isn't specific to the type of line, you could have your strategy classes just parse the line and return a parsed form, and let the caller do the saving in one place.
Another variant of this pattern is for the strategy class to have a method accepts?
that takes the item to be worked on and returns true or false without actually doing anything to it, and a second method that actually does the work.