Rake + Sake: Thor

Picture of a hammer

Thor is a Ruby scripting framework fresh from the fevered imagination of Yehuda Katz. It allows you to do all of the things that Rake and Sake have become popular for, with the added bonus of letting you write it all in regular Ruby syntax.

Let me show you what I mean. First install the Thor gem -

sudo gem install thor

Here is a Thor script that let’s me open Ruby gem directories in TextMate; something that I find myself doing quite often.

gemate.thor

 1 # module: gemate
 2 
 3 class Gemate < Thor
 4   
 5   desc "view NAME", "view gem directory in TextMate"
 6   def view(name)
 7   
 8     term = name + '*'
 9 
10     puts "Searching for '" + term + "'..."
11 
12     # get the path to the gem directory from rubygems and search for any matching directories
13     path = `gem env gemdir`
14     new_path = File.join([path.chomp, 'gems'])
15     Dir.chdir(new_path)
16     @d_arr = Dir.glob(term)
17 
18     if @d_arr.empty?
19       puts "Sorry, nothing like that found"
20     elsif @d_arr.size == 1
21       view_one()
22     else
23       view_list()
24     end
25   end
26     
27   private
28   
29     def view_one
30       puts @d_arr.first
31       print 'Do you want to view this? [Y/n]: '
32       resp = gets.chomp!
33       if resp.empty? or resp.downcase == 'y'
34         exec "mate #{@d_arr.first}"
35       end
36     end
37     
38     def view_list
39       @d_arr.each_with_index {|d,i| puts "#{i + 1}: #{d}"}
40       puts
41       print 'Choose a directory or quit(q): '
42       idx = gets.chomp!
43       if idx.downcase == 'q'
44         exit
45       elsif (1..@d_arr.size).include?(idx.to_i)
46         exec "mate #{@d_arr.at(idx.to_i - 1)}"
47       else
48         puts 'not a valid option'
49       end
50     end
51 
52 end

I invoke the script like this -

thor gemate:view GEM_NAME

Yehuda wrote a blog post that introduces Thor and provides a brief explanation of some of it’s features. There is also a GitHub repository that you can take a peek at if you’re interested enough.

The Force is strong with this one …

Permalink | comments(View)

blog comments powered by Disqus