Namespaces

From $1

Table of contents
No headers

After an assembly has been loaded with load or require, it’s top-level namespaces and classes are available to IronRuby. Given the following C# code compiled to models.dll:

namespace Models {
  public class Person {
    private string name;
    public Person(string name) {
      this.name = name;
    }
    public string Name { 
      get {
        return name;
      }
    }
  }
}

The “Models” namespace can be accessed from IronRuby just as you would with a Ruby Module; with its name as a Ruby constant:

>>> require 'models'
=> true
>>> Models
=> Models
>>> Models.class
=> Module

There are some cases where IronRuby won’t see a namespace:

  1. Lowercase namespace: Ruby constants are required to be an uppercase letter follow by name characters, namespaces must also fit that description to be used in IronRuby.
  2. “Empty” namespace: For IronRuby to see a namespace is must not be empty, as CLR namespaces only exists with visible children. A namespace is still non-existent to IronRuby if it has all private/internal children, so it must have at least one publically visible class.

Because Namespaces act just as Ruby Modules, they can be used as mixins for any Ruby class:

class MyApp
  include Models
end

This is less interesting for a CLR Namespace, as they can only contain classes, where Ruby Modules can have classes, methods, or anything else. However, it is useful as an equivalent to C#’s “using” keyword to bring a namespace’s classes into the current scope:

>>> include Models
=> Object
>>> Person
=> Models::Person


There is a caviate here; because of how Ruby resolves constant names, any constant that already exists in that scope will not be included.

>>> include System
=> Object
>>> AppDomain
=> System::AppDomain
>>> Math
=> Math

Where is System::Math!? Because Ruby has a Math module already, it wasn't included. If you want to get access to System::Math, you can either use the full System::Math name, or set a new constant to hold onto it

>>> SMath = System::Math
=> System::Math
Tags:
 
Images (0)
 
Comments (1)
Viewing 1 of 1 comments: view all
Viewing 1 of 1 comments: view all
You must login to post a comment.

 
SourceForge.net