Tuesday, October 16, 2007

Cheap Tricks X - Managing Ruby Gems from MediaWiki

In Cheap Tricks III I relayed a little script I wrote to keep everyone at work in sync concerning groups of ruby gems. As the number of projects expanded I was forced to also expand the way we managed that list - other than passing it around or requiring everyone to svn update. Thanks to a little-known MediaWiki action, we are able to keep a list in the wiki.

require 'net/http'
require 'yaml'

def gem_install(gem, version, url=nil)
# only install if not already installed
listed = `gem list #{gem} --no-details --local`
unless listed =~ %r"^#{gem} "
puts "== Installing #{gem}"
puts `sudo gem install #{gem} -f -y -v '#{version}'`
end
end

# First try and find a local or given gems.yml file
gems_config_file = ARGV[0].nil? ? 'gems.yml' : ARGV[0]
gems = nil
begin
gems = YAML::load_file( gems_config_file )
rescue Errno::ENOENT => e
puts "Could not find file... looking remotely in the wiki Gems.yml"

url = URI.parse('http://wikiserver/')
res = Net::HTTP.start(url.host, url.port) do |http|
http.get("/index.php?action=raw&title=Gems.yml")
end
data = res.body
gems = YAML::load(data)
end
gems['gems'].each { |gem| gem_install(gem[0], gem[1]) }
If the gems.yml cannot be found locally and is not passed in as an argument, then the script will grab the YAML file from the wiki, in an article entitled Gems.yml. The yml file has the same structure as any other YAML file... it just lives in the wiki. Notice in the URL I have "action=raw". This is a MediaWiki command to return the raw article data, not rendered. If you don't have MW, you can equally put this into something like Subversion and grab it that way. Whatever.

As an added bonus, I updated the gem_install method to skip gems that were previously installed.

Happy "Cheap Tricks" #10 Day! Huzzah!

0 comments: