RubyGems, IronRuby and System::Net namespace

Recently I encountered an interesting gotcha with IronRuby. I wanted to use a rubygem together with the WebRequest CLR object from the System.Net namespace. I had my require and include statements set as shown below.

require ‘rubygems’
# Additional require statements
require ‘mscorlib’
require ‘System, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089’
include System

With this in place, I could happily access my gems and CLR objects. However, when I attempt to access WebRequest it failed. The code was correct as I had it working in a different sample.

request = Net::WebRequest.Create(@url)

However, this whenever I tried in the current sample I was getting a NameError, meaning IronRuby was unable to find the class.

E:IronRubysrcIronRuby.LibrariesBuiltinsModuleOps.cs:721:in `const_missing’: uninitialized constant Net::WebRequest (NameError)
        from :0

After a little trial and error, I found that the reason it wasn’t working was because I had included RubyGems, this gave me access to ruby’s standard library. Within the standard library, there is a namespace called Net which has all of the standard objects you would expect for dealing with network communication (net::http, net::telnet etc). As a result, Ruby and .Net clashed with Ruby taking priority, meaning I couldn’t access Net::WebRequest.

The workaround is to be more explicit about what you want. You either need to include the System.Net namespace, include System::Net,  or add System when attempting to access the object, System::Net::WebRequest. You will then be able to access the object as normal.

Technorati Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *