Ruby Fileutils Alias on MAC

How to create directories recursively in ruby?

Use mkdir_p:

FileUtils.mkdir_p '/a/b/c'

The _p is a unix holdover for parent/path you can also use the alias mkpath if that makes more sense for you.

FileUtils.mkpath '/a/b/c'

In Ruby 1.9 FileUtils was removed from the core, so you'll have to require 'fileutils'.

Errno::ENOENT: No such file or directory ruby

You can't save to a non-existing path. As the developer you're responsible to make sure your destination paths exist prior to trying to save the file.

Ruby has methods that let you check for the existence a file or directory:

  • File.exist?('path/to/file')
  • File.file?('path/to/file')
  • File.directory?('path/to/file')
  • Dir.directory?('path/to/dir')
  • Dir.mkdir('path/to/dir')
  • FileUtils.makedirs('path/to/dir')

FileUtils.makedirs() is an alias to mkpath, and mkdir_p. I prefer makedirs because it's a mnemonic.

These will also be useful:

  • Dir.chdir('path/to/dir')
  • FileUtils.chdir('path/to/dir')

Between those two I prefer Dir.chdir, because it takes a block. Any actions that occur inside that block happen in the directory you changed to. At exit, the directory reverts to what it was previously.

Carrierwave upload hits Errno::EEXIST - file exists error

This is a pitfall when creating an OS-X 'alias' instead of a symlink.

(Not in the actual gems resp. any specific version – I experienced the same today with rails 5.0.0.1, ruby 3.2.1 and carrierwave 0.11.2.)

It turned out that I had accidently created not a symlink but an alias using the OS X Finder (which technically is not a symlink). When carrierwave then tries to create the folder structure FileUtils.mkir_p raises an error on trying to (re)create the (existing) alias as a directory.

rm ./app/releases/20141018152115/public/uploads
ln -s ./app/shared/public/uploads ./app/releases/$timestamp/public/uploads

should do the trick.

[EDIT: Clarified the actual root cause is not in ruby, rails or the gems in use]

What is the structure of the rails generate command?

You need to start going through the Rails source code to understand the generators. For example, here are the usage instructions for rails generate model: https://github.com/rails/rails/blob/master/railties/lib/rails/generators/rails/model/USAGE

And here is the actual generator: https://github.com/rails/rails/blob/master/railties/lib/rails/generators/rails/model/model_generator.rb

Interestingly, you can override any and all of these generators, which I've used to generate a lot of custom test templates off an existing schema.rb.

This Rails Guide covers customizing generators.

How do I move a file with Ruby?

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.



Related Topics



Leave a reply



Submit