From: Mauricio Fernandez Date: 2006-08-29T17:39:52+09:00 Subject: Re: Including a class. On Tue, Aug 29, 2006 at 05:02:10PM +0900, Ola Bini wrote: > As an extension on my earlier question of partial includes; I just > noticed that you can't include a Class, even though it is a Module. > > Anyone have a way of doing this? > > What I would like to do, is to be able to dynamically mix in some good > methods from preexisting classes, depending on arguments to the > constructor. Since I need to do it dynamically, and also need it > differently for different instances of the class, I can't make it > inherit the other class. [...] > But I can't have an instance of Bar or Foo so delegating is impossible. ======================== > I need the methods to be in the the same instance. Doesn't this provide a very strong indication that you want to put the reusable methods in modules? :-) RUBY_VERSION # => "1.8.5" RUBY_RELEASE_DATE # => "2006-08-25" module A; def foo; "A#foo" end end module B; def foo; "B#foo" end end class X; include A end class Y; include B end class Z def initialize(config = {}) if config[:A] extend A elsif config[:B] extend B end end end Z.new(:A => true).foo # => "A#foo" Z.new(:B => true).foo # => "B#foo" [See [211308] for a Module#append_from implementation that doesn't clobber inherited methods.] -- Mauricio Fernandez - http://eigenclass.org - singular Ruby