Including Namespaces


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


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'

You might write this:

	require 'rexml/document'
	include REXML



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'"Some XML")

You might write this:

	require 'rexml/parsers/pullparser'
	include REXML::Parsers"Some XML")


See Also

  • Recipe 11.3, "Extracting Data While Parsing a Document"



Date and Time



Files and Directories

Code Blocks and Iteration

Objects and Classes8

Modules and Namespaces

Reflection and Metaprogramming


Graphics and Other File Formats

Databases and Persistence

Internet Services

Web Development Ruby on Rails

Web Services and Distributed Programming

Testing, Debugging, Optimizing, and Documenting

Packaging and Distributing Software

Automating Tasks with Rake

Multitasking and Multithreading

User Interface

Extending Ruby with Other Languages

System Administration

Ruby Cookbook
Ruby Cookbook (Cookbooks (OReilly))
ISBN: 0596523696
EAN: 2147483647
Year: N/A
Pages: 399

Similar book on Amazon © 2008-2020.
If you may any questions please contact us: