Question

I have a controller in Rails, with an action that is meant to create a new directory.

This action should create the directory "/public/graph_templates/aaa/test". However it leaves off the final directory "test". Why is this only creating parent directories?

  def create_temporary_template
    dir = File.dirname("#{Rails.root}/public/graph_templates/aaa/test")
    FileUtils.mkdir_p dir
  end

Docs: http://ruby-doc.org/stdlib-1.9.3/libdoc/fileutils/rdoc/FileUtils.html#method-c-mkdir_p

Was it helpful?

Solution

Because you use dir = File.dirname("#{Rails.root}/public/graph_templates/aaa/test"),

then the dir is "#{Rails.root}/public/graph_templates/aaa".

You could just pass the path to FileUtils.mkdir_p.

  def create_temporary_template
    dir = "#{Rails.root}/public/graph_templates/aaa/test"
    FileUtils.mkdir_p dir
  end

OTHER TIPS

The problem is in your use of dirname:

File.dirname("/foo/bar")
# => "/foo"

dirname removes the last entry from the path. Per the documentation:

Returns all components of the filename given in file_name except the last one.

Usually that's the correct thing if your path contains a directory, or directory hierarchy, with the filename:

File.dirname("/foo/bar/baz.txt")
# => "/foo/bar"

But, in this case it's chopping off your desired trailing directory.

I'd recommend taking a look at the Pathname class that is included in Ruby's Standard Library. It wraps File, Dir, FileUtils, FileTest, and probably a Swiss-Army knife and kitchen sink into one class, making it very convenient to work on files and directories with one class.

require 'pathname'
dir = Pathname.new("/foo/bar/baz.txt")
# => "/foo/bar"

dir.mkpath # would create the path

I've found Pathname to be very useful, though it's still young.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top