(C) John Mair (banisterfiend) 2010
Scoped modification of core classes
Add temporary functionality to core classes.
Based on some ideas found in this Ruby-Forum thread
Tweak provides the
using method we can enhance a core class for the duration
of a block:
module Tweaks class String def hello :hello end end class Fixnum Hello = :hello def bye :bye end end end using Tweaks do "john".hello #=> :hello 5.bye #=> :bye Fixnum::Hello #=> :hello end "john".hello #=> NameError
How it works
Makes use of the
Object2module libraries. Note that
modifies core classes by what is effectively a module inclusion, this
means you cannot use
Tweak to override existing functionality but
more to augment and supplement that functionality.
Tweak works by doing the following:
- Looks for top-level classes and modules with the same name as those defined under the using-module.
Object2moduleto include the corresponding class/module defined under the using-module into the top-level class/module of the same name.
Remixto uninclude that functionality at the end of the
Also look at the Remix library's
temp_extend methods for a more general solution than
Tweak is not threadsafe.
Does not work with nested modules, e.g
This is not intended to be a robust or serious solution, it's just a little experiment. :)
Tweak is one of a series of experimental libraries that mess with the internals of Ruby to bring new and interesting functionality to the language, see also:
- Remix - Makes ancestor chains read/write
- Object2module - Enables you to include/extend Object/Classes.
- Include Complete - Brings in module singleton classes during an include. No more ugly ClassMethods and included() hook hacks.
- Prepend - Prepends modules in front of a class; so method lookup starts with the module
- GenEval - A strange new breed of instance_eval
- LocalEval - instance_eval without changing self
Problems or questions contact me at github