On Thu, Jun 2, 2011 at 6:34 PM, Chad Perrin <code / apotheon.net> wrote:
> On Thu, Jun 02, 2011 at 10:51:46PM +0900, Peter Zotov wrote:
>>
>> It failed because __FILE__ is not a constant: it is a special lexical
>> construct which is replaced by just a string containing the filename at
>> the point of _loading_ the file, i.e. even before the execution begins.
>> You simply cannot access it in any way after the file was loaded.
>>
>> You can still implement it this way (note that it may not work on
>> implementations other
>> than MRI):
>
> [snip]
>
> This seems to work just fine:
>
> =A0 =A0module Kernel
> =A0 =A0 =A0def executed?
> =A0 =A0 =A0 =A0__FILE__ =3D=3D $0
> =A0 =A0 =A0end
> =A0 =A0end
>
> =A0 =A0if executed?
> =A0 =A0 =A0puts 'awesomesauce'
> =A0 =A0else
> =A0 =A0 =A0puts 'failsauce'
> =A0 =A0end
>
> What am I missing in the constraints of the request?

He wants to have the definition of the executed? method in a different
file, which gets required in his main file, and the problem is that
__FILE__ then it's evaluated to the name of the other file, not the
main file.

A solution, which I don't know if it feels clean enough would be to
pass that to the method:

#executed.rb
module Kernel
  def executed? file=3D__FILE__
    file =3D=3D $0
  end
end

#main.rb
require 'executed'
if executed? __FILE__
  puts "Executed"
else
  puts "Loaded"
end

$ ruby main.rb
Executed
$ ruby -rmain -e ""
Loaded


Jesus.