Thor purports to replace Rake and Sake, at least for system scripting. It can do the same things Rake and Sake can do, but it does them while actually looking like (mostly) plain Ruby, and, on top of that, it makes dealing with command line options and argument super freakin’ simple. I’ll admit, I was on the fence about Thor until actually writing this script:
\# module: rlogclass RLog \< Thor
desc 'stats FILE', 'view reqs/sec stats from a Rails log'
def stats(file)puts"Parsing \#{file}..."
reqs\_per\_sec = parse\_log\_file(file)putssprintf("%-7s %d reqs/sec", 'Mean:', mean(reqs\_per\_sec))putssprintf("%-7s %d reqs/sec", 'Median:', median(reqs\_per\_sec))putssprintf("%-7s %d reqs/sec", 'Mode:', mode(reqs\_per\_sec))end
private
def parse\_log\_file(file)\# Log Analyzing Task
log = File.open(file)
reqs\_per\_sec = \[\]
log.each\_linedo |line|
parts = line.scan(/(\\d+)(\\sreqs\\/sec)/)\# There should only be one match per line... right?
reqs\_per\_sec \<\< parts\[0\]\[0\].to\_iunless parts\[0\].nil?
end
reqs\_per\_sec
enddef mean(reqs\_per\_sec)
sum = reqs\_per\_sec.inject{|sum, x| sum + x }
sum/reqs\_per\_sec.sizeenddef median(reqs\_per\_sec)
sum = reqs\_per\_sec.inject{|sum, x| sum + x }
reqs\_per\_sec\[(reqs\_per\_sec.size/2).to\_i\]enddef mode(reqs\_per\_sec)\# Find the mode
nums = {}
reqs\_per\_sec.eachdo |r|
unless nums.include?(r)
nums\[r\] ||= 0
nums\[r\] += 1endend
nums.sort{|a, b| a\[1\] \<=\> b\[1\]}.last\[0\]endend
I am going to assume you haven’t installed Thor. If you have, you know which step to skip:
Thor is cool. There’s no doubt about it. It does indeed make dealing with options in Ruby scripts trivial (although I obviously haven’t really used that yet), and it’s nice that it is less DSL and more plain Ruby. I don’t understand why Thor hasn’t gotten the same amount of love that Sake got when it was debuted. It makes me wonder if people love the Rake DSL more than they love Ruby. Sinners!Blasphemers!Hipsters! If I can make Thor do anything I would want to do with Sake, or, even better, anything I would want to do with any old bash script, then I am sure I will be using Thor quite often. You should, too.
Where was I? Oh, right, the Rails log stat scripts. Yup. There they are. What do you think? Seriously, what could be added (that it would make sense to add to a Rake/Sake/Thor script)? What have I done horribly wrong? How poor is my Rubyisms knowledge? Tell me!
I’ll leave you with the most common Thor (from Marvel Comics, if you hadn’t gotten it by now) phrase: