tags:

views:

73

answers:

4

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} #{@DEST_DIR}/#{file}")

Is it possible to do this in Ruby? If so, what is the correct syntax?

+1  A: 
system("mv #{@SOURCE_DIR}/#{my_file} #{@DEST_DIR}/#{file})

should be the correct call

Aurril
+4  A: 

Hi,

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!

Chris McCauley
Ok, thank you for all the answers.If I move and rename the file over NFS file system, what does really happen after File.rename? Does File.rename pull the file to my local file system and rename it and push(move) it back to destination or it does the rename operation on destination?
Niklas
The remote NFS server is responsible for handling the rename. As far as all local programs are concerned, the file is local but it's the job of the NFS driver to make it appear as if it were local.Files are never copied locally for rename or move operations.
Chris McCauley
+1  A: 

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
SMiX
+3  A: 

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.

Andrew Grimm