Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get __FILE__ of compiled script

How can I get the compiled version of my Crystal script to get its own __FILE__. Here is an example. I have a file called ~/test.cr with the following contents:

puts __FILE__

I compile the script via Crystal

~$ crystal ~/test.cr -o ~/test.compiled

Next I run ~/test.compiled. I produces the result

/Users/Account1/test.cr

even though the __FILE__ is actually

/Users/Account1/test.compiled

Is there a way to make it produce

/Users/Account1/test.compiled

Instead of

/Users/Account1/test.cr
like image 412
Some Dinosaur Avatar asked Mar 12 '23 21:03

Some Dinosaur


1 Answers

The meta constant __FILE__ always point to the source file, not the executable. However, you can use $0 to get the current executable path (or the full path using File.expand_path):

foo.cr:

puts $0
puts File.expand_path($0)

Then compile and execute:

$~ crystal build foo.cr
$~ ./foo
./foo
/Users/MyUser/foo
like image 61
waj Avatar answered Mar 19 '23 14:03

waj