Class: Stockboy::Readers::FixedWidth
- Inherits:
-
Stockboy::Reader
- Object
- Stockboy::Reader
- Stockboy::Readers::FixedWidth
- Defined in:
- lib/stockboy/readers/fixed_width.rb
Overview
For reading fixed-width data split by column widths
Options collapse
-
#encoding ⇒ String
Override original file encoding.
-
#headers ⇒ Array<Fixnum>, Hash{Object=>Fixnum}
Widths of data columns with optional names.
-
#row_format ⇒ Fixnum
Number of file rows to skip at end of file.
-
#skip_footer_rows ⇒ Fixnum
Number of file rows to skip from start of file.
-
#skip_header_rows ⇒ String
String format used for unpacking rows.
Instance Method Summary collapse
-
#initialize(opts = {}, &block) ⇒ FixedWidth
constructor
Initialize a new fixed-width reader.
- #parse(data) ⇒ Object
Constructor Details
#initialize(opts = {}, &block) ⇒ FixedWidth
Initialize a new fixed-width reader
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
#encoding ⇒ String
Override original file encoding
58 |
# File 'lib/stockboy/readers/fixed_width.rb', line 58 dsl_attr :encoding |
#headers ⇒ Array<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.
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 .times { records.pop } records end |
#row_format ⇒ Fixnum
Number of file rows to skip at end of file
Useful if the file ends with a summary or notice
52 |
# File 'lib/stockboy/readers/fixed_width.rb', line 52 dsl_attr :row_format |
#skip_footer_rows ⇒ Fixnum
Number of file rows to skip from start of file
Useful if the file starts with a preamble or header metadata
44 |
# File 'lib/stockboy/readers/fixed_width.rb', line 44 dsl_attr :skip_footer_rows |
#skip_header_rows ⇒ String
String format used for unpacking rows
This is read from the #headers attribute by default but can be overridden
36 |
# File 'lib/stockboy/readers/fixed_width.rb', line 36 dsl_attr :skip_header_rows |