Class: Amazon::Util::DataReader

Inherits:
Object
  • Object
show all
Defined in:
lib/amazon/util/data_reader.rb

Overview

DataReader is a class for loading in data files. It is used to support bulk file-based operations. DataReader supports a number of different formats:

  • YAML

  • Tabular

  • CSV

  • Java Properties

By default, DataReader assumes Tabular, but load and save both support your choice of format

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data = []) ⇒ DataReader

Returns a new instance of DataReader.



22
23
24
# File 'lib/amazon/util/data_reader.rb', line 22

def initialize(data=[])
  @data = data
end

Instance Attribute Details

#dataObject

Returns the value of attribute data.



20
21
22
# File 'lib/amazon/util/data_reader.rb', line 20

def data
  @data
end

Class Method Details

.load(filename, format = :Tabular) ⇒ Object



69
70
71
72
# File 'lib/amazon/util/data_reader.rb', line 69

def self.load( filename, format=:Tabular )
  reader = DataReader.new()
  reader.load( filename, format )
end

.save(filename, data, format = :Tabular, force_headers = false) ⇒ Object



74
75
76
77
# File 'lib/amazon/util/data_reader.rb', line 74

def self.save( filename, data, format=:Tabular, force_headers=false )
  reader = DataReader.new( data )
  reader.save( filename, format, force_headers )
end

Instance Method Details

#[](index) ⇒ Object



26
27
28
# File 'lib/amazon/util/data_reader.rb', line 26

def [](index)
  return @data[index]
end

#[]=(index) ⇒ Object



30
31
32
# File 'lib/amazon/util/data_reader.rb', line 30

def []=(index)
  return @data[index]
end

#load(filename, format = :Tabular) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/amazon/util/data_reader.rb', line 34

def load( filename, format=:Tabular )
  return {} unless File.exist? filename
  raw_data = File.read( filename )
  case format
  when :Tabular
    @data = parse_csv( raw_data, "\t" )
  when :YAML
    @data = YAML.load( raw_data ) || {}
  when :CSV
    @data = parse_csv( raw_data )
  when :Properties
    @data = parse_properties( raw_data )
  else
    raise "invalid format.  options are :Tabular, :YAML, :CSV, :Properties"
  end
end

#save(filename, format = :Tabular, force_headers = false) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/amazon/util/data_reader.rb', line 51

def save( filename, format=:Tabular, force_headers=false )
  return if @data.nil? or @data.empty?
  existing = File.exist?( filename ) && File.size( filename ) > 0
  File.open( filename, 'a+' ) {|f| 
    f << case format
    when :Tabular
      generate_csv( @data, force_headers || !existing, "\t" )
    when :YAML
      YAML.dump( @data )
    when :CSV
      generate_csv( @data, force_headers || !existing )
    when :Properties
      generate_properties( @data )
    end
    f << "\n" # adding a newline on the end, so appending is happy
  }
end