Recipe 9.6. Automatically Loading Libraries as NeededProblemYou've written a big library with multiple components. You'd like to split it up so that users don't have to load the entire library into memory just to use part of it. But you don't want to make your users explicitly require each part of the library they plan to use. SolutionSplit the big library into multiple files, and set up Suppose you have a library, functions.rb, that provides two very large modules:
You can provide the same interface, but possibly save your users some memory, by splitting functions.rb into three files. The functions.rb file itself becomes a stub full of
The modules themselves go into the files mentioned in the new functions.rb:
The following code will work if all the modules are in functions.rb, but it will also work if functions.rb only contains calls to autoload:
When Decidable and Semidecidable have been split into autoloaded modules, that code only loads the Decidable module. Memory is saved that would otherwise be used to contain the unsed Semidecidable module. DiscussionRefactoring a library to consist of autoloadable components takes a little extra planning, but it's often worth it to improve performance for the people who use your library. Each call to Kernel#autoload binds a symbol to the path of the Ruby file that's supposed to define that symbol. If the symbol is referenced, that file is loaded exactly as though it had been passed as an argument into require. If the symbol is never referenced, the user saves some memory. Since you can use autoload wherever you might use require, you can autoload builtin
If random_set is never called, the set library will never be loaded, and memory will be saved. As soon as random_set gets called, the set library is autoloaded, and the code works even though we never explicitly require 'set':
|
Thursday, October 22, 2009
Recipe 9.6. Automatically Loading Libraries as Needed
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment