From: Peter Zotov Date: 2011-06-02T22:51:46+09:00 Subject: Re: CORE - Replace "if __FILE__ == $0" with "executed?" On Thu, 2 Jun 2011 22:30:27 +0900, Ilias Lazaridis 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 try to implement a method in Kernel > > #myib.rb > module Kernel > def executed? > # detect in a clean way if the caller calls from an executed file > # return true if so, else return false > end > end > > #maintest.rb > require 'mylib' > if executed? > print "works nice" > else > print "seems to fail > end > > What would be the code for executed? > > I tried this way: > def executed? > f = eval '__FILE__', TOPLEVEL_BINDING > p = eval '$0', TOPLEVEL_BINDING > return f == p > end > > but this failed somehow, and I dislike it. 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): # mylib.rb module Kernel def executed? caller.last =~ /^(.*):\d+$/ && $0 == $1 end end # test.rb require 'mylib' if executed? puts "Executed" else puts "Loaded" end Test it with: $ ruby test.rb; ruby -rtest -e "" Executed Loaded -- WBR, Peter Zotov.