enhance classes with temporary functionality
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Failed to load latest commit information.



(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.

example: using

With the using method we can enhance a core class for the duration of a block:

module Tweaks

  class String
    def hello

  class Fixnum
    Hello = :hello

    def bye


using Tweaks do
  "john".hello #=> :hello
  5.bye #=> :bye
  Fixnum::Hello #=> :hello

"john".hello #=> NameError

How it works

Makes use of the Remix and Object2module libraries. Note that Tweak 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.
  • Uses Object2module to include the corresponding class/module defined under the using-module into the top-level class/module of the same name.
  • Uses Remix to uninclude that functionality at the end of the using block.

Also look at the Remix library's temp_include and temp_extend methods for a more general solution than Tweak.

Thread Safety

Tweak is not threadsafe.


Does not work with nested modules, e.g class String::SomethingElse

This is not intended to be a robust or serious solution, it's just a little experiment. :)

Companion Libraries

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