I am new to Ruby, I’m writing a script that does the following:
- Accepts command line arguments
- Deletes a few directories based on specifying an argument.
What I want it to do:
./admin_bin -c
Removing files in /opt/sysnovo/tmp and /opt/sysnovo/data
I have this working! But… it’s not in a rubyish way.
Here is my code:
#!/usr/bin/env ruby
require 'rubygems'
require 'fileutils'
require 'optparse'
OptionParser.new do |o|
o.on('-c') { |b| $clear = b }
o.on('-h') { puts o; exit }
o.parse!
end
# Two directories we want to specify.
tmp_dir = "/opt/sysnovo/tmp"
data_dir = "/opt/sysnovo/data"
# push this value to a variable so we can evaluate it.
test = $clear
if "#{test}" == "true"
puts "Removing files in #{tmp_dir} and #{data_dir}"
FileUtils.rm_rf("#{tmp_dir}/.", secure: true)
FileUtils.rm_rf("#{data_dir}/.", secure: true)
else
puts "Not removing files."
end
As you can see, I set $clear to #{test} and evaluate based on that. I know it’s not correct. What’s the correct way to do this? I’ll be adding more arguments and functionality to this script later on.
P.S. I come from a bash background.
Option Parser use the True/False class to set the flags. You test should look like this :
If you do
$clear.class=> TrueClass. It’s a bool.You also only need to
require 'rubygems'if you are using ruby <1.9.