Module: Gzr::FileHelper

Instance Method Summary collapse

Instance Method Details

#read_file(file_name) {|data_hash || {}| ... } ⇒ Object

Yields:

  • (data_hash || {})


67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/gzr/modules/filehelper.rb', line 67

def read_file(file_name)
  file = nil
  data_hash = nil
  begin
    file = (file_name.kind_of? StringIO) ? file_name : File.open(file_name)
    data_hash = JSON.parse(file.read,{:symbolize_names => true})
  ensure
    file.close if file
  end
  return (data_hash || {}) unless block_given?

  yield data_hash || {}
end

#write_file(file_name = nil, base_dir = nil, path = nil, output = $stdout) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/gzr/modules/filehelper.rb', line 29

def write_file(file_name=nil,base_dir=nil,path=nil,output=$stdout)
  f = nil
  if base_dir.respond_to?(:mkdir)&& base_dir.respond_to?(:add_file) then
    if path then
      @archived_paths ||= Array.new
      base_dir.mkdir(path.to_path, 0755) unless @archived_paths.include?(path.to_path)
      @archived_paths << path.to_path
    end
    fn = Pathname.new(file_name.gsub('/',"\u{2215}"))
    fn = path + fn if path
    base_dir.add_file(fn.to_path, 0644) do |tf|
      yield tf
    end
    return
  end

  base = Pathname.new(File.expand_path(base_dir)) if base_dir
  begin
    p = Pathname.new(path) if path
    p.descend do |path_part|
      test_dir = base + Pathname.new(path_part)
      Dir.mkdir(test_dir) unless (test_dir.exist? && test_dir.directory?)
    end if p
    file = Pathname.new(file_name.gsub('/',"\u{2215}")) if file_name
    file = p + file if p
    file = base + file if base
    f = File.open(file, "wt") if file
  end if base

  return ( f || output ) unless block_given?
  begin
    yield ( f || output )
  ensure
    f.close if f
  end
  nil
end