On Feb 17, 2011, at 8:40 PM, Anurag Priyam wrote:

>> Hi Folks - I am running some ruby tests and would like to print out
>> the actual test to the console or store it to a file.  The tests are
>> written as classes with a setup, run, and teardown method.
>> So here's my question: is there a way to get the class definition or
>> method definitions as a "string", so that I can print it out (to a
>> file or console)?
>> I know ruby supports a lot of reflection (like .methods
>> or .constants), but I'm not seeing how to do this.
>=20
> A very non-elegant, trivial way using Ruby's DATA stream ;) :
>=20
> # test.rb
> def foo
>  puts "hi"
> end
>=20
> flag =3D nil
> DATA.tap{|x| x.rewind}.readlines.each do |line|
>  flag =3D true if line =3D~ /^def/
>  puts line if flag
>  flag =3D false if line =3D~ /^end/
> end
> __END__
>=20
> $ ruby test.rb
> def foo
>  puts "hi"
> end
>=20
> Obviously you will have to come up with better heuristics to determine
> the end of a method.
>=20

In Ruby 1.9, you can retrieve the place where the method was defined =
using #source_location:

  def foo

  end
 =20
  method(:foo).source_location #=3D> ["file.rb", 1]

The same goes for procs:

  def foo(&block)
    puts block.source_location.inspect
  end

  foo do

  end #=3D> ["file.rb", 5]

Regards,
Florian