Good Morning,

On Thu, Jun 2, 2011 at 6:30 AM, Ilias Lazaridis <ilias / lazaridis.com> wrote:

> The construct to detect execution of the file (in order to launch main
> code) looks like this:
>
> if __FILE__ == $0
>  main
> end
>
> I would like a more elegant code.
>

I believe the following works but I always get myself into trouble in these
areas so I may fall flat on my face here.

#test.rb
module Kernel
  def executed?
    caller[0].split(':')[0] == $0
  end
end

#test2.rb
require_relative './test.rb'

if executed?
  puts 'Hello there'
else
  puts 'try again'
end

#test3.rb
require_relative './test2'

ruby test2.rb
Hello there
ruby test3.rb
try again

#caller holds the stack including the file name of the caller so I believe
you can use that instead of __FILE__ in this case.

I tested this on ruby 1.9 but I believe it works in 1.8 as well.

John