Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run code only if script called from the command line

So when I call my script from the command line, I want it to take in an int and do something with the value:

ruby script.rb   puts ARGV[0], etc... 

However, whenever the script is loaded or required and not called from command line, I want to completely skip this part of the code. How can I detect whether the script has been called via command line, or just loaded? Thanks!

like image 430
srchulo Avatar asked Jan 24 '12 16:01

srchulo


1 Answers

It is common to put this at the bottom of your script:

if __FILE__==$0   # this will only run if the script was the main, not load'd or require'd end 

Because I like to see the main action at the top of my file, I usually put a def run! as the first method in the file and then end the file with:

run! if __FILE__==$0 
like image 92
Phrogz Avatar answered Sep 30 '22 05:09

Phrogz