Class: IOStreams::Tabular::Parser::Fixed
- Defined in:
- lib/io_streams/tabular/parser/fixed.rb
Overview
Parsing and rendering fixed length data
Defined Under Namespace
Classes: FixedLayout
Instance Attribute Summary collapse
-
#fixed_layout ⇒ Object
readonly
Returns the value of attribute fixed_layout.
Instance Method Summary collapse
-
#initialize(layout:) ⇒ Fixed
constructor
Returns [IOStreams::Tabular::Parser].
-
#parse(line) ⇒ Object
Returns [Hash<Symbol, String>] fixed layout values extracted from the supplied line.
-
#render(row, header) ⇒ Object
Returns [String] fixed layout values extracted from the supplied hash.
Methods inherited from Base
Constructor Details
#initialize(layout:) ⇒ Fixed
Returns [IOStreams::Tabular::Parser]
Parameters:
layout: [Array<Hash>]
[
{key: 'name', size: 23 },
{key: 'address', size: 40 },
{key: 'zip', size: 5 }
]
17 18 19 |
# File 'lib/io_streams/tabular/parser/fixed.rb', line 17 def initialize(layout:) @fixed_layout = parse_layout(layout) end |
Instance Attribute Details
#fixed_layout ⇒ Object (readonly)
Returns the value of attribute fixed_layout.
6 7 8 |
# File 'lib/io_streams/tabular/parser/fixed.rb', line 6 def fixed_layout @fixed_layout end |
Instance Method Details
#parse(line) ⇒ Object
Returns [Hash<Symbol, String>] fixed layout values extracted from the supplied line. String will be encoded to ‘encoding`
37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/io_streams/tabular/parser/fixed.rb', line 37 def parse(line) unless line.is_a?(String) raise(IOStreams::Errors::TypeMismatch, "Format is :fixed. Invalid parse input: #{line.class.name}") end hash = {} index = 0 fixed_layout.each do |map| value = line[index..(index + map.size - 1)] index += map.size hash[map.key] = value.to_s.strip end hash end |
#render(row, header) ⇒ Object
Returns [String] fixed layout values extracted from the supplied hash. String will be encoded to ‘encoding`
23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/io_streams/tabular/parser/fixed.rb', line 23 def render(row, header) hash = header.to_hash(row) result = '' fixed_layout.each do |map| # A nil value is considered an empty string value = hash[map.key].to_s result << format("%-#{map.size}.#{map.size}s", value) end result end |