Wednesday, January 16, 2013

Admin Script Controller - Ruby Command Line Tool

I use a lot of custom made scripts at work to make my life a little easier (or to be lazier, whichever) and sometimes have trouble finding a specific one. My solution was to make a command line interface to control the assorted scripts. To implement grab all the needed scripts and drop them in a folder with this script. To make it a bit more user friendly I suggest making a bash alias like so, alias utility="ruby ~/Documents/Code/utility-scripts/utility.rb".


[sourcecode language="ruby"]
#! /usr/bin/ruby
abort("Usage: `utility <script name>` or `utility list` to list") unless script = ARGV[0]
basedir = File.expand_path File.dirname(__FILE__)
puts %x(tree #{basedir}) if script == 'list'
interpreters = {'.rb'=>'ruby','.php'=>'php','.sh'=>'sh'}

Dir.new(File.dirname(__FILE__)).each do |file|
unless ['.', '..'].include? file
if script == File.basename(file, File.extname(file))
ext = File.extname(file)
command = "#{interpreters[ext]} #{basedir}/#{script}#{ext} #{ARGV[1]} #{ARGV[2]} #{ARGV[3]}"
puts "Calling: #{command}"
exec command unless script == 'utility'
end
end
end
[/sourcecode]

No comments:

Post a Comment