From: Robert Klemme Date: 2009-12-29T23:37:42+09:00 Subject: Re: Using #include at the instance level? 2009/12/29 Intransition : > > > On Dec 29, 3:29 am, Robert Klemme wrote: >> 2009/12/29 Intransition : >> >> >> >> > I would like to use #include at an instance level, such that it >> > behaves just as it does at a class level. After a number of >> > experiments I thought for sure it would work if I ran the include >> > through the object's singleton. Alas, submodules remain inaccessible, >> > eg. >> >> >  module M >> >    def m1; "m1"; end >> >    module N >> >      def self.n1; "n1"; end >> >    end >> >  end >> >> >  class X >> >    def initialize(*mods) >> >      (class << self; self; end).class_eval do >> >        include *mods >> >      end >> >    end >> >    def m ; m1 ; end >> >    def n ; N.n1 ; end >> >> Hm, this method above won't work as scope resolution rules for >> constants are different. >> >> >  end >> >> >  x = X.new(M) >> >  p x.m >> >  p x.n    #=> uninitialized constant X::N (NameError) >> >> > Is there any way to achieve this? >> >> Did you consider using #extend? >> >>  class X >>    def initialize(*mods) >>      extend *mods >>    end >> end >> >> What do you really want to achieve?  Do you have a more telling example? > > It's for encapsulating test cases. Eg. > >  TestCase.new(SomeClass) do >    ... >  end > > Within the test case block it would help to handle #include, to make > tests less verbose. I see to be a bit slow today: how do you want to use modules there? Do you want to include them in the test code? What about: class TestCase def new(cl, &bl) @cl = cl instance_eval(&bl) end alias include extend end TestCase.new String do extend Foo include Bar end > Instead of making an instance of TestCase for each case, at this point > it looks like I'll have to create a new subclass of it. Sorry, you lost me here. Cheers robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/