IronRuby – a SharePoint Developer’s Best Friend

I wrote a while back about SharePoint scripting with IronPython. Well today’s announcement of the first binary release of IronRuby got me pretty darn excited. I really like Python, but I LOVE Ruby. I’ve been waiting for IronRuby to catch up to IronPython for quite a while and it looks like they’re getting close.

Here’s a quick guide to getting up and running with IronRuby and SharePoint.

Installation:

  1. First, download the IronRuby release from Rubyforge.
  2. Next, copy the ironruby folder you extract to your Program Files (put it wherever you like – that’s where I put mine).
  3. Update your system’s PATH environment variable to contain the path to the ironruby\bin folder.  So if you placed it in your Program Files, you would add this to your PATH: c:\program files\ironruby\bin

Creating a Script:

Next you’ll want to create a new text file called print_sites.rb. I recommend the e text editor by the way – great tool.  Add the following lines to your file:

require 'System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL'
require 'Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c, processorArchitecture=MSIL'

Uri = System::Uri
SPSite = Microsoft::SharePoint::SPSite
SPWebApplication = Microsoft::SharePoint::Administration::SPWebApplication

Okay – what does that do? Well the first two lines are like adding a reference to a standard Visual Studio project. They tell IronRuby that we need to reference (require) the System and Microsoft.SharePoint assemblies. The next three lines are for convenience. They set up aliases to the System.Uri class and two SharePoint classes. In our ruby code, now we can just use Uri, SPSite, etc instead of having to type out the fully qualified path.

Next, let’s add some ruby code to enumerate all sites in a web application.

webapp = SPWebApplication.Lookup(Uri.new("http://localhost"))
webapp.Sites.each do |site|
  puts site.Url
end

(hmm, looks like I don’t actually need the SPSite alias after all)

Now, save your file. You can execute it like this:

> ir print_sites.rb

If everything is set up right, you should see the URL for each site collection be printed to the screen.

There you go. Have fun.