Module: Gzr::FileHelper

Instance Method Summary collapse

Instance Method Details

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

Yields:

  • (data_hash || {})


78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/gzr/modules/filehelper.rb', line 78

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



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
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/gzr/modules/filehelper.rb', line 30

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) || base_dir.respond_to?(:get_output_stream)) then
    if path then
      @archived_paths ||= Array.new
      begin
        base_dir.mkdir(path.to_path, 0755) unless @archived_paths.include?(path.to_path)
      rescue Errno::EEXIST => e
        nil
      end
      @archived_paths << path.to_path
    end
    fn = Pathname.new(file_name.gsub('/',"\u{2215}"))
    fn = path + fn if path
    if base_dir.respond_to?(:add_file)
      base_dir.add_file(fn.to_path, 0644) do |tf|
        yield tf
      end
    elsif base_dir.respond_to?(:get_output_stream)
      base_dir.get_output_stream(fn.to_path, 0644) do |zf|
        yield zf
      end
    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}").gsub(':','')) 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