Cover by David Flanagan, Yukihiro Matsumoto

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

Missing Methods and Missing Constants

The method_missing method is a key part of Ruby’s method lookup algorithm (see Method Lookup) and provides a powerful way to catch and handle arbitrary invocations on an object. The const_missing method of Module performs a similar function for the constant lookup algorithm and allows us to compute or lazily initialize constants on the fly. The examples that follow demonstrate both of these methods.

Unicode Codepoint Constants with const_missing

Example 8-3 defines a Unicode module that appears to define a constant (a UTF-8 encoded string) for every Unicode codepoint from U+0000 to U+10FFFF. The only practical way to support this many constants is to use the const_missing method. The code makes the assumption that if a constant is referenced once, it is likely to be used again, so the const_missing method calls Module.const_set to define a real constant to refer to each value it computes.

Example 8-3. Unicode codepoint constants with const_missing

# This module provides constants that define the UTF-8 strings for # all Unicode codepoints. It uses const_missing to define them lazily. # Examples: # copyright = Unicode::U00A9 # euro = Unicode::U20AC # infinity = Unicode::U221E module Unicode # This method allows us to define Unicode codepoint constants lazily. def self.const_missing(name) # Undefined constant passed as a symbol # Check that the constant name is of the right form. # Capital U followed by a hex number between 0000 and 10FFFF. if name.to_s ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required