How do I move a file with Ruby? - ruby

I want to move a file with Ruby. How do I do that?

You can use FileUtils to do this.
#!/usr/bin/env ruby
require 'fileutils'
FileUtils.mv('/tmp/your_file', '/opt/new/location/your_file')
Remember; if you are moving across partitions, "mv" will copy the file to new destination and unlink the source path.

An old question, i'm surprised no one answered this simple solution. You don't need fileutils or a systemcall, just rename the file to the new location.
File.rename source_path, target_path
Happy coding

FileUtils.move
require 'fileutils'
FileUtils.move 'stuff.rb', '/notexist/lib/ruby'

Use the module 'fileutils' and use FileUtils.mv:
http://www.ruby-doc.org/stdlib-2.0/libdoc/fileutils/rdoc/FileUtils.html#method-c-mv

here is a template .
src_dir = "/full_path/to_some/ex_file.txt"
dst_dir = "/full_path/target_dir"
#Use the method below to do the moving
move_src_to_target_dir(src_dir, dst_dir)
def archive_src_to_dst_dir(src_dir, dst_dir)
if File.exist ? (src_dir)
puts "about to move this file: #{src_dir}"
FileUtils.mv(src_dir, dst_dir)
else
puts "can not find source file to move"
end
end

you can move your file like this
Rails.root.join('foo','bar')

Related

How to change a file's path within ruby

I'm trying to move files from one folder to another via Ruby, but I'm stuck trying to get Pathname.new to work. For reference the files are being held in array as an inbetween from their normal dir. I know I could move it via CLI but I'd like the program to do it for me. This is what I have so far. I know it's wrong; I just don't get how to fix it.
temp_array.each {|song| song.path(Pathname.new("/Users/tsiege/Desktop/#{playlist_name}"))}
Have a look at FileUtils.mv:
require 'fileutils'
temp_array.each do |song|
FileUtils.mv song.path, "/Users/tsiege/Desktop/#{playlist_name}"
end
Be sure that the directory #{playlist_name} exists before you do, though:
FileUtils.mkdir_p "/Users/tsiege/Desktop/#{playlist_name}"
To move files you can use FileUtils.mv:
require 'fileutils'
FileUtils.mv 'from.ext', 'to.ext'
http://ruby-doc.org/stdlib-1.9.3/libdoc/fileutils/rdoc/FileUtils.html#method-c-mv
And if you want a list of files in a directory you can use:
Dir['/path/to/dir/*']
http://ruby-doc.org/core-1.9.3/Dir.html
Lastly, you may also want to check if you have a file or directory:
File.file? file
File.directory? dir
http://ruby-doc.org/core-1.9.3/File.html#method-c-file-3F

Ruby deleting directories

I'm trying to delete a non-empty directory in Ruby and no matter which way I go about it it refuses to work.
I have tried using FileUtils, system calls, recursively going into the given directory and deleting everything, but always seem to end up with (temporary?) files such as
.__afsECFC
.__afs73B9
Anyone know why this is happening and how I can go around it?
require 'fileutils'
FileUtils.rm_rf('directorypath/name')
Doesn't this work?
Safe method: FileUtils.remove_dir(somedir)
Realised my error, some of the files hadn't been closed.
I earlier in my program I was using
File.open(filename).read
which I swapped for a
f = File.open(filename, "r")
while line = f.gets
puts line
end
f.close
And now
FileUtils.rm_rf(dirname)
works flawlessly
I guess the best way to remove a directory with all your content "without using an aditional lib" is using a simple recursive method:
def remove_dir(path)
if File.directory?(path)
Dir.foreach(path) do |file|
if ((file.to_s != ".") and (file.to_s != ".."))
remove_dir("#{path}/#{file}")
end
end
Dir.delete(path)
else
File.delete(path)
end
end
remove_dir(path)
The built-in pathname gem really improves the ergonomics of working with paths, and it has an #rmtree method that can achieve exactly this:
require "pathname"
path = Pathname.new("~/path/to/folder").expand_path
path.rmtree

how to choose file with certain extension? ruby

I want ruby to look for a file in the current folder that ends with a certain extension. The extension would be .app.zip
How would I do this?
To get the first matching file in the current directory, you can use:
file=Dir['*.app.zip'].first
Or to find all .app.zip files in certain directory, for example files/*.app.zip, you can use something like :
Dir[File.join('files', '*.app.zip')].each |file|
puts "found: #{file}"
end
Alternative to Dir:
require "find"
Find.find(folder) do |file|
puts "#{file}" if file=~/\.app\.zip/
end

Is it possible to recursively require all files in a directory in Ruby?

I am working on an API that needs to load all of the .rb files in its current directory and all subdirectories. Currently, I am entering a new require statement for each file that I add but I would like to make it where I only have to place the file in one of the subdirectories and have it automatically added.
Is there a standard command to do this?
In this case its loading all the files under the lib directory:
Dir["#{File.dirname(__FILE__)}/lib/**/*.rb"].each { |f| load(f) }
require "find"
Find.find(folder) do |file|
next if File.extname(file) != ".rb"
puts "loading #{file}"
load(file)
end
This will recursively load each .rb file.
like Miguel Fonseca said, but in ruby >= 2 you can do :
Dir[File.expand_path "lib/**/*.rb"].each{|f| require_relative(f)}
I use the gem require_all all the time, and it gets the job done with the following pattern in your requires:
require 'require_all'
require_all './lib/exceptions/'
def rLoad(dir)
Dir.entries(dir).each {|f|
next if f=='.' or f=='..'
if File.directory?(f)
rInclude(f)
else
load(f) if File.fnmatch('*.rb', f)
end
}
end
This should recursively load all .rb files in the directory specified by dir. For example, rLoad Dir.pwd would work on the current working directory.
Be careful doing this, though. This does a depth-first search and if there are any conflicting definitions in your Ruby scripts, they may be resolved in some non-obvious manner (alphabetical by folder/file name I believe).
You should have a look at this gem. It is quite small so you can actually re-use the code instead of installing the whole gem.

Best way to require all files from a directory in ruby?

What's the best way to require all files from a directory in ruby ?
How about:
Dir["/path/to/directory/*.rb"].each {|file| require file }
If it's a directory relative to the file that does the requiring (e.g. you want to load all files in the lib directory):
Dir[File.dirname(__FILE__) + '/lib/*.rb'].each {|file| require file }
Edit: Based on comments below, an updated version:
Dir[File.join(__dir__, 'lib', '*.rb')].each { |file| require file }
Try the require_all gem:
http://github.com/jarmo/require_all
https://rubygems.org/gems/require_all
It lets you simply:
require_all 'path/to/directory'
Dir[File.dirname(__FILE__) + '/../lib/*.rb'].each do |file|
require File.basename(file, File.extname(file))
end
If you don't strip the extension then you may end up requiring the same file twice (ruby won't realize that "foo" and "foo.rb" are the same file). Requiring the same file twice can lead to spurious warnings (e.g. "warning: already initialized constant").
Dir.glob(File.join('path', '**', '*.rb'), &method(:require))
or alternatively, if you want to scope the files to load to specific folders:
Dir.glob(File.join('path', '{folder1,folder2}', '**', '*.rb'), &method(:require))
explanation:
Dir.glob takes a block as argument.
method(:require) will return the require method.
&method(:require) will convert the method to a bloc.
The best way is to add the directory to the load path and then require the basename of each file. This is because you want to avoid accidentally requiring the same file twice -- often not the intended behavior. Whether a file will be loaded or not is dependent on whether require has seen the path passed to it before. For example, this simple irb session shows that you can mistakenly require and load the same file twice.
$ irb
irb(main):001:0> require 'test'
=> true
irb(main):002:0> require './test'
=> true
irb(main):003:0> require './test.rb'
=> false
irb(main):004:0> require 'test'
=> false
Note that the first two lines return true meaning the same file was loaded both times. When paths are used, even if the paths point to the same location, require doesn't know that the file was already required.
Here instead, we add a directory to the load path and then require the basename of each *.rb file within.
dir = "/path/to/directory"
$LOAD_PATH.unshift(dir)
Dir[File.join(dir, "*.rb")].each {|file| require File.basename(file) }
If you don't care about the file being required more than once, or your intention is just to load the contents of the file, perhaps load should be used instead of require. Use load in this case, because it better expresses what you're trying to accomplish. For example:
Dir["/path/to/directory/*.rb"].each {|file| load file }
Instead of concatenating paths like in some answers, I use File.expand_path:
Dir[File.expand_path('importers/*.rb', File.dirname(__FILE__))].each do |file|
require file
end
Update:
Instead of using File.dirname you could do the following:
Dir[File.expand_path('../importers/*.rb', __FILE__)].each do |file|
require file
end
Where .. strips the filename of __FILE__.
Dir[File.join(__dir__, "/app/**/*.rb")].each do |file|
require file
end
This will work recursively on your local machine and a remote (Like Heroku) which does not use relative paths.
In Rails, you can do:
Dir[Rails.root.join('lib', 'ext', '*.rb')].each { |file| require file }
Update: Corrected with suggestion of #Jiggneshh Gohel to remove slashes.
I'm a few years late to the party, but I kind of like this one-line solution I used to get rails to include everything in app/workers/concerns:
Dir[ Rails.root.join *%w(app workers concerns *) ].each{ |f| require f }
And what about: require_relative *Dir['relative path']?

Resources