Environment and CLI
| ENV variables | |
| ARGV | |
| OptionParser | |
| Exit codes |
ENV variables
Programs read their configuration from ENV, which maps process environment variables by name.
Fetch with a fallback keeps development simple while production passes the real value.
mode = ENV.fetch("APP_MODE", "development")
puts mode
APP_MODE=production ruby app.rb
production
ARGV
Command line arguments arrive in ARGV as an array of strings.
Length counts the arguments and first reads the leading one.
puts ARGV.length
puts ARGV.first
ruby args.rb one two
2
one
OptionParser
OptionParser turns flags such as verbose into an options hash with help text built in.
The on call registers each flag, and parse! consumes the flags from ARGV.
require "optparse"
options = { verbose: false }
OptionParser.new do |parser|
parser.on("-v", "--verbose", "Run verbosely") do
options[:verbose] = true
end
end.parse!
p options
ruby flags.rb --verbose
{:verbose=>true}
Exit codes
A nonzero exit status signals failure to the shell and to calling scripts.
Warn writes the complaint to standard error, and exit 1 stops the program with status 1.
if ARGV.empty?
warn("Need a file name")
exit(1)
end
puts "Got #{ARGV.first}"
ruby check.rb
Need a file name
Next: Logging
Article author: Arthur Isaev