IronShay

Ironing code, geek t-shirts and even presentations!

NAVIGATION - SEARCH

Working with .NET Lowercase Namespaces and Classes in IronRuby

[if you have no idea what IronRuby is, read this first]

.NET has some common naming conventions that everybody uses. One of them is that namespace and class names are PascalCased. However, like in real life – rules are meant to be broken. In C#/VB.NET there is no real constraint on this convention – you can name your namespaces/classes using all lowercase or in any other way you want (and I ask, why?). Therefore, the next C# code is totally acceptable:

namespace demo
{
  class library
  {
    public void Print()
    {
      Console.WriteLine("Yay! I've broken the rulez! I'm a smartass!");
    }
  }
}

The Problem

Unlike C#/VB.NET, in Ruby you must start namespace (which is called a module) and class names with a capital letter. And there you have it – clash of the titans.

Clash of the Titans  
Now, normally you wouldn’t care about that but if you’re using IronRuby, you’re right in the middle here. On the one hand, you’d expect IronRuby to allow you to use .NET classes with their original names but on the other hand, the Ruby language just doesn’t allow that.

The Solution

To solve this issue we must use some kind of a workaround. Luckily, IronRuby provide a pretty simple workaround. For example, consider the next C# classes (let’s assume this code is built into an assembly named demo.dll):

namespace demo
{
  public class library
  {
    public void Print()
    {
      Console.WriteLine("Hello");
    }
  }

  public class LibraryWithGoodName
  {
    public void Print()
    {
      Console.WriteLine("Hello");
    }
  }
}

This is how you use it from IronRuby:

require "demo.dll"

# Get the namespace object
Demo = Object.const_get("demo")

# Get the lowercase library class object
Library = Demo.const_get("library")

# Use the library class:
lib = Library.new
lib.Print

# Another alternative to create a library class instance in one line:
lib = Object.const_get("demo").const_get("library").new
lib.Print

# Use the LibraryWithGoodName class:
lib1 = Demo::LibraryWithGoodName.new
lib1.Print

All the best,
Shay.



Pingbacks and trackbacks (1)+

Add comment