System call in Ruby
I'm a beginner in ruby and in programming as well and need help with system call for moving a file from source to destination like this:
system(mv "#{@SOURCE_DIR}/#{my_file开发者_StackOverflow} #{@DEST_DIR}/#{file}")
Is it possible to do this in Ruby? If so, what is the correct syntax?
system("mv #{@SOURCE_DIR}/#{my_file} #{@DEST_DIR}/#{file})
can be replaced with
system("mv", "#{@SOURCE_DIR}/#{my_file}", "#{@DEST_DIR}/#{file}")
which reduces the chances of a command line injection attack.
Two ways
Recommended way
You can use the functions in the File Utils libary see here to move your files e.g
mv(src, dest, options = {})
Options: force noop verbose
Moves file(s) src to dest. If file and dest exist on the different disk
partition, the file is copied instead.
FileUtils.mv 'badname.rb', 'goodname.rb'
FileUtils.mv 'stuff.rb', '/notexist/lib/ruby', :force => true # no error
FileUtils.mv %w(junk.txt dust.txt), '/home/aamine/.trash/'
FileUtils.mv Dir.glob('test*.rb'), 'test', :noop => true, :verbose => true
Naughty way
Use the backticks approach (run any string as a command)
result = `mv "#{@SOURCE_DIR}/#{my_file} #{@DEST_DIR}/#{file}"`
Ok, that's just a variation of calling the system command but looks much naughtier!
system("mv #{@SOURCE_DIR}/#{my_file} #{@DEST_DIR}/#{file})
should be the correct call
I recommend you to use Tanaka akira's escape library Here is example from one my app:
cmd = Escape.shell_command(['python', Rails::Configuration.new.root_path + '/script/grab.py']).to_s
system cmd
精彩评论