If Modules have one property that Classes envy it would be their ability for dynamic inclusion in an inheritance chain. Using Object2module, however, we can gift our Classes (and Objects) with identical functionality.

How to use:

require 'object2module' class MyClass def hello_world puts "hello world!" end end o = Object.new o.extend MyClass.to_module o.hello_world #=> "hello world!"

Since including and extending ‘modulified’ Objects is likely the aim of a user, two functions are provided for this purpose.

gen_extend() and gen_include() are generalizations of the ordinary extend() and include() methods and are capable of including/extending Objects and Classes as well as Modules.

require 'object2module' class MyClass def hello_world puts "hello world!" end end #using gen_extend o = Object.new o.gen_extend MyClass o.hello_world #=> "hello world!" #using gen_include class Fren gen_include MyClass end Fren.new.hello #=> "hello world!"

How it works:

Object2module works by first creating an IClass for the Class in question and setting the T_MODULE flag.

It then recursively converts superclasses of the Class to IClasses (up to but excluding Object) creating a modulified version of the inheritance chain.

In the case of Objects the same process is followed as above except it begins with the eigenclass of the Object.

Download:

Install the gem: sudo gem install object2module

git project: http://github.com/banister/object2module/tree/master

Applications:

For one application of Object2module check out Dup_eval

Share this: Twitter

Facebook

Reddit

Like this: Like Loading... Related