Recipe 9.3. Mixing in Class MethodsCredit: Phil Tomson ProblemYou want to mix class methods into a class, instead of mixing in instance methods. SolutionThe simplest way to accomplish this is to call extend on the class object, as seen in the Discussion of Recipe 9.2. Just as you can use extend to add singleton methods to an object, you can use it to add class methods to a class. But that's not always the best option. Your users may not know that your module provides or even requires some class methods, so they might not extend their class when they should. How can you make an include statement mix in class methods as well? To begin, within your module, define a submodule called ClassMethods,[3]which contains the methods you want to mix into the class:
To make this code work, we must also define the included callback method within the MyLib module. This method is called every time a module is included in the class, and it's passed the class object in which our module is being included. Within the
Now we can include our MyLib module in a class, and get the contents of ClassMethods mixed in as genuine class methods:
Discussion The Object#extend method takes a Module object as a parameter. It mixes all the methods defined in the module into the receiving object. Since classes are themselves objects, and the singleton methods of a Class object are just its class methods, calling extend on a class object fills it up with new class methods. See Also
|
Thursday, October 22, 2009
Recipe 9.3. Mixing in Class Methods
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment