Hi --

On Sun, 10 Nov 2002, Tom Clarke wrote:

>
> I was wondering about the possibility of being able to temporarily replace
> a class with another (to be able to easily mock a class like File for
> example).
>
> I found an implementation of pose_as on a posting from this list
> describing an implementation for pose_as:
> http://www.ruby-talk.org/cgi-bin/vframe.rb/ruby/ruby-talk/20008?19808-25362
>
> Matz had followed up with showing that you can do:
> 	OldClass = NewClass
>
> This doesn't work within a set_up method (Dynamic Constant Assignment) and
> also doesn't let me put the old one back in the teardown.
>
> The pose_as implementation seems to have a problem or two, and before I
> try and debug it, is there:
> 	a) a good implementation somewhere, or
> 	b) a similarly simple way to OldClass=NewClass that I can use in a
> dynamic context

Hmmm... this seems too weird to be good, but anyway, have a look:

  class B
    def talk
      puts "Hi"
    end
  end

  class A
    def set_up
      "#{File = B}"     # this is the weird part.  eval works too.
      f = File.new
      f.talk
    end
  end

  A.new.set_up   # Hi


You get a warning with this, but it runs.

Is there some way you can use the Mock class?  (I'm very ignorant of
it, but it's around somewhere.)


David

-- 
David Alan Black
home: dblack / candle.superlink.net
work: blackdav / shu.edu
Web:  http://pirate.shu.edu/~blackdav