From: Brian Candler Date: 2003-08-02T18:45:58+09:00 Subject: Re: Anonymous, single instance class creation On Sat, Aug 02, 2003 at 06:13:55PM +0900, Nathaniel Talbott wrote: > I find myself doing the following in tests a lot: > > some_external_object = Object.new > def some_external_object.some_method > ... do some stuff ... > end > > OR: > > some_external_object = Object.new > class << some_external_object > def some_method > ... do some stuff ... > end > end > > Is there a way to do that more concisely? Perhaps to eliminate the separate > Object.new? You can encapsulate the method in a Module: module MyModule def some_method ... do stuff ... end end some_external_object = Object.new some_external_object.extend MyModule But I don't understand why you are creating a new instance of Object and then extending it. The traditional way to add methods to Object is simply to create a class containing those methods: class MyClass # < Object [implied] def some_method ... do stuff ... end end some_thing = MyClass.new # = Object.new plus the methods in MyClass You say you do this in tests a lot (test/unit?) Can you give a more concrete example? I can't see why class MyTest < Test::Unit::TestCase def some_method ... end ... rest of tests end doesn't do the business. The test framework will generate an instance of MyTest in order to run it, and therefore this instance will have some_method available. Otherwise, you define another class Foo, and in your initialize method create an instance of it: def initialize @some_external_object = Foo.new end > Also, is there a way to let the methods be more like closures, i.e.: > > a = "stuff" > > some_external_object = Object.new > def some_external_object.some_method > a #from external scope > end > > assert_equal(a, method_under_test(some_external_object)) > > That would make it even more powerful. If you find yourself needing that, usually the 'right' solution is to make 'a' into an instance variable (@a) of some object. Again, I'd like to see the code which makes use of the above pattern. Are you using local variables inside a class but outside a method?? class MyTest < Test::Unit::TestCase a = "stuff" def some_method a # ?? end end because if so, maybe you just want class MyTest < Test::Unit::TestCase def initialize @a = "stuff" end def some_method @a end end You *can* achieve what you want, though, using define_method which converts a proc object into a method. The example at the bottom of http://www.rubygarden.org/ruby?SingletonTutorial might help. I also valuely remember that 1.8 might let you pass a block to 'def'. Regards, Brian.