Including Namespaces

Problem

You want to use the objects within a module without constantly qualifying the object names with the name of their module.

Solution

Use include to copy a module's objects into the current namespace. You can then use them from the current namespace, without qualifying their names.

Instead of this:

require 'rexml/document' REXML::Document.new(xml)

You might write this:

require 'rexml/document' include REXML Document.new(xml)

 

Discussion

This is the exact same include statement you use to incorporate a mixin module into a class you're writing. It does the same thing here as when it includes a mixin: it copies the contents of a module into the current namespace.

Here, though, the point isn't to add new functionality to a class or module: it's to save you from having to do so much typing. This technique is especially useful with large library modules like Curses and the Rails libraries.

This use of include comes with the same caveats as any other: if you already have variables with the same names as the objects being included, the included objects will be copied in over them and clobber them.

You can, of course, import a namespace that's nested within a namespace of its own. Instead of this:

require 'rexml/parsers/pullparser' REXML::Parsers::PullParser.new("Some XML")

You might write this:

require 'rexml/parsers/pullparser' include REXML::Parsers PullParser.new("Some XML")

 

See Also

Категории