Module: Grizzled::FileUtil

Defined in:
lib/grizzled/fileutil.rb,
lib/grizzled/fileutil/ziputil.rb,
lib/grizzled/fileutil/includer.rb

Overview

This module and its submodules contain various file-related utility methods.

Defined Under Namespace

Modules: ZipUtil Classes: BadDirectoryTreeKey, BadDirectoryTreeValue, IncludeException, IncludeSource, Includer

Instance Method Summary collapse

Instance Method Details

#make_directory_tree(directory, tree) ⇒ Object

Create a file/directory hierarchy. The hash table specifies the entries, using the following rules.

  • A hash entry whose value is another hash table is taken to be a directory and will be recursively created.

  • A hash entry with a String value is a file, whose contents are the string.

  • A hash entry with an Enumerable value is a file, whose contents are the enumerable values, rendered as strings.

  • Anything else is an error.

For instance, this hash:

tree = {"foo" =>
          {"bar"   => {"a" => "File a's contents",
                       "b" => "File b's contents"},
           "baz"   => {"c" => "Blah blah blah"},
           "xyzzy" => "Yadda yadda yadda"}}

results in this directory tree:

foo/
    bar/
        a   # File a's contents
        b   # File a's contents

    baz/
        c   # Blah blah blah

    xyzzy   # Yadda yadda yadda

The keys should be simple file names, with no file separators (i.e., no parent directories).

Parameters:

directory

The starting directory, which is created if it does not exist.

tree

The entry tree, as described above

Returns:

A Dir object for directory, for convenience.



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/grizzled/fileutil.rb', line 98

def make_directory_tree(directory, tree)

  require 'fileutils'

  if File.exists? directory
    if not File.directory? directory
      raise BadDirectoryTreeKey.new("Directory '#{directory}' already " +
                                    "exists and isn't a directory.")
    end
  else
    Dir.mkdir directory
  end

  FileUtils.cd directory do
    tree.each do |entry, contents|
      if entry.include? File::SEPARATOR
        raise BadDirectoryTreeKey.new("File tree key '#{key}' contains " +
                                      "illegal file separator character.");
      end

      # Must test Hash first, because Hash is Enumerable.

      if contents.kind_of? Hash
        # This is a directory
        make_directory_tree(entry, contents)

      elsif contents.kind_of? Enumerable
        f = File.open(File.join(entry), 'w')
        contents.each {|thing| f.write(thing.to_s)}
        f.close

      else
        raise BadDirectoryTreeValue.new(entry, contents)
      end
    end
  end

  return Dir.new(directory)
end