Forum: Ruby Recursive directory rename problem

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Ransom T. (Guest)
on 2009-02-06 00:55
Problem:
- trying to standardize on a naming convention for all of my
directories(OS agnostic).
- new structure should be all lower-case with hyphphens for spaces
- Using windows, I am running the following:


 Dir.foreach("./"){ |d|
      next if d =~ /[a-z]+\.[a-z]+/
      next if d == "." or d == ".."
      d.downcase!
      newfile = d.gsub(/\W/, "-")
      File.rename(d, newfile)
      }

so I want:

\Test Dir1
\TestDir2\TestDir 1

to change to

\test-dir1
\testdir2\testdir-1




Which works fine on the top level, but is not recursing down to the next
level. Filenames should be ignored.

I've tried playing with various methods on the Dir class (entries,
etc..).
Using Dir[**/**] is throwing up saying that it can't rename (no surprise
since it can't rename without an absolute path, I guess).

Please help thanks!
Mike G. (Guest)
on 2009-02-06 07:05
Ransom T.:
> so I want:
>
> \Test Dir1
> \TestDir2\TestDir 1
>
> to change to
>
> \test-dir1
> \testdir2\testdir-1
>
> Which works fine on the top level, but is not recursing down to the
> next level. Filenames should be ignored.

Dir.entries is not recursive; you want 'find'.  But it has to be a
depth-first 'find': you can gradually replace the pillars of a
building if you start from the top, but not from the bottom.  (Mixing
metaphors on which direction is 'depth'.)

  require 'pathname'

  def find_depth_first(pathname)
    acc = []
    pathname.find { |file| acc << file }
    acc.reverse!
    acc.each { |path| yield path }
  end

  find_depth_first(Pathname(".")) { |path|
    if path.directory?
      new_path = path.dirname +
        Pathname(path.basename.to_s.downcase.gsub(/\s/, "-"))
      if new_path != path
        path.rename(new_path)
      end
    end
  }
This topic is locked and can not be replied to.