Class: Stockboy::Readers::FixedWidth

Inherits:
Stockboy::Reader show all
Defined in:
lib/stockboy/readers/fixed_width.rb

Overview

For reading fixed-width data split by column widths

Options collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}, &block) ⇒ FixedWidth

Initialize a new fixed-width reader

Parameters:

  • opts (Hash) (defaults to: {})

Options Hash (opts):

  • headers (Array<Fixnum>, Hash<Fixnum>)
  • skip_header_rows (Fixnum)
  • skip_footer_rows (Fixnum)
  • encoding (String)


70
71
72
73
74
75
76
# File 'lib/stockboy/readers/fixed_width.rb', line 70

def initialize(opts={}, &block)
  super
  @headers          = opts[:headers]
  @skip_header_rows = opts.fetch(:skip_header_rows, 0)
  @skip_footer_rows = opts.fetch(:skip_footer_rows, 0)
  DSL.new(self).instance_eval(&block) if block_given?
end

Instance Method Details

#encodingString

Override original file encoding

Returns:

  • (String)


58
# File 'lib/stockboy/readers/fixed_width.rb', line 58

dsl_attr :encoding

#headersArray<Fixnum>, Hash{Object=>Fixnum}

Widths of data columns with optional names

Array format will use numeric indexes for field keys. Hash will use the keys for naming the fields.

Examples:

reader.headers = [10, 5, 10, 42]
reader.parse(data)
#=> [{0=>"Arthur", 1=>"42", 2=>"Earth", 3=>""}]

reader.headers = {name: 10, age: 5, planet: 10, notes: 42}
reader.parse(data)
#=> [{name: "Arthur", age: "42", planet: "Earth", notes: ""}]

Returns:

  • (Array<Fixnum>, Hash{Object=>Fixnum})


27
# File 'lib/stockboy/readers/fixed_width.rb', line 27

dsl_attr :headers

#parse(data) ⇒ Object



78
79
80
81
82
83
84
85
86
87
88
# File 'lib/stockboy/readers/fixed_width.rb', line 78

def parse(data)
  @column_widths, @column_keys = nil, nil
  data.force_encoding(encoding) if encoding
  data = StringIO.new(data) unless data.is_a? StringIO
  skip_header_rows.times { data.readline }
  records = data.reduce([]) do |a, row|
    a.tap { a << parse_row(row) unless row.strip.empty? }
  end
  skip_footer_rows.times { records.pop }
  records
end

#row_formatFixnum

Number of file rows to skip at end of file

Useful if the file ends with a summary or notice

Returns:

  • (Fixnum)


52
# File 'lib/stockboy/readers/fixed_width.rb', line 52

dsl_attr :row_format

Number of file rows to skip from start of file

Useful if the file starts with a preamble or header metadata

Returns:

  • (Fixnum)


44
# File 'lib/stockboy/readers/fixed_width.rb', line 44

dsl_attr :skip_footer_rows

#skip_header_rowsString

String format used for unpacking rows

This is read from the #headers attribute by default but can be overridden

Returns:

  • (String)


36
# File 'lib/stockboy/readers/fixed_width.rb', line 36

dsl_attr :skip_header_rows