Module: Treebis::DirAsHash

Included in:
Test::TestCase
Defined in:
lib/treebis.rb

Defined Under Namespace

Classes: Blacklist

Class Method Summary collapse

Class Method Details

.dir_as_hash(path, opts = {}) ⇒ Object

Return an entire filsystem node as a hash whose files are represented as strings holding the contents of the file and whose folders are other such hashes. The hash element keys are the entry strings. Careful! the only real use for this so far is in testing.



141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/treebis.rb', line 141

def dir_as_hash path, opts={}
  blacklist = Blacklist.get(opts[:skip])
  list1 = Dir.new(path).each.map.reject{ |x|
    0==x.index('.') || blacklist.include?(x)
  }
  list2 = list1.map{ |entry|
    p = path + '/' + entry
    [ entry, File.directory?(p) ?
      dir_as_hash(p, :skip=>blacklist.submatcher(entry)) : File.read(p) ]
  }
  Hash[ list2 ]
end

.hash_to_dir(hash, path, file_utils = FileUtils) ⇒ Object



155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
# File 'lib/treebis.rb', line 155

def hash_to_dir hash, path, file_utils=FileUtils
  fail("must not exist: #{path}") if File.exist? path
  file_utils.mkdir_p(path,:verbose=>true)
  hash.each do |k,v|
    path2 = File.join(path, k)
    case v
    when String
      File.open(path2, 'w'){|fh| fh.write(v)}
    when Hash
      hash_to_dir(v, path2, file_utils)
    else
      fail("bad type for dir hash: #{v.inspect}")
    end
  end
  true
end