Tonight Blaine sent me his version of my Simple Ruby Log splitter, that took it a giant step further and made a reuseable library to split files. He used an object oriented approach, as well as provided extensibility by allowing the caller to pass in a block that determined when to split the file. Hopefully he will post the code either on my site or his.
Good stuff.
Anyway, he brought that problem back into my head, and I immediately thought about making a DSL for splitting files. The code I came up with is below.
Note: I am hoping to share ideas here. If anyone has a better way to do this please please please either post your thoughts/code in the comments or blog about it and send me the link. I am still very much learning Ruby, and would love to see what other people are doing.
-
#
-
# read from $stdin, splitting it into multiple files, using a DSL of sorts
-
#
-
def nextFile(filename, count)
-
File.open(“#{count}_#{filename}”, “w”)
-
end
-
-
def split(instream, filename, args)
-
currentFile = nil
-
lines = count = 0
-
lineBreak = args[:lines].to_i
-
instream.each do |line|
-
currentFile = nextFile(filename, count+=1) if (lines%lineBreak) == 0
-
lines += 1
-
currentFile.write line
-
end
-
end
-
-
def parse(command)
-
command.gsub(/into|when/, “,”).gsub(/=/,“=>”) # overly simplistic, no error handling, etc
-
end
-
-
def run(command)
-
eval parse(command)
-
end
-
-
run “split $stdin into ’split.log’ when :lines = 1000″
Of course, one quick look at this will show that this example is simplistic, and that there is much work that could be done to make it more robust and/or full featured. That is not the point. The point is line 27, where your business-tier developers only need to type in near-english syntax to get their jobs done. The rest of it is not too hard in this case… though it can get much much harder in other cases. However, that can be handled by a relatively few developers, and greatly simplifies the work for the rest.
Anyone care to take this example further?
p.s.> I know there is some work being done on DSL books for Ruby. I cannot wait until I get my hands on one. If anyone out there needs a reviewer, drop me a line. 