Object2module: Converting Ruby Objects to Modules

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

About these ads

3 Responses to “Object2module: Converting Ruby Objects to Modules”

  1. I assume this only works with MRI then?

Trackbacks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: