From: Jeff Rose Date: 2006-06-08T20:42:01+09:00 Subject: Re: Why the lack of mixing-in support for Class methods? Alder Green wrote: > Hi > > I'm confused as to why class methods aren't include'd by default along > with instance methods when mixing-in modules. > > It obstructs the important orthoganility between modules and classes, > and - among other problems - thus undermines the position of mixins as > an alternative to class-based multiple inheritance. > > In short, I can see a lot of poor consequence to that lack of support, > while on the other hand no good reason for it. Maybe someone would > care to elighten me? > > (I'm aware of the various hacks for fudging such support, and in fact > use some of them in my code. But there are readability and > maintainability issues with those hacks for something that's supposed > to be a core feature). > You can do this without too much trouble. This is what I use, which is based off some code _why posted on his blog a while back. ---- meta.rb ---- # A set of methods to help create meta-programming gizmos. class Object # The metaclass is the singleton behind every object. def metaclass class << self self end end # Evaluates the block in the context of the metaclass def meta_eval &blk metaclass.instance_eval &blk end # Acts like an include except it adds the module's methods # to the metaclass so they act like class methods. def meta_include mod meta_eval do include mod end end # Adds methods to a metaclass def meta_def name, &blk meta_eval { define_method name, &blk } end # Defines an instance method within a class def class_def name, &blk class_eval { define_method name, &blk } end end ---------------------- require 'meta' module Foo def test puts "test method" end end class Bar meta_include Foo end Bar.test # >> "test method\n" -Jeff