module TxtData::FormatHelpers

A helpful module for formatting fields for fixed length txt data files.

Public Instance Methods

filter_illegal_characters(value) click to toggle source

Filters invalid characters specified in CPF eSubmission spec file. @param [String] value

# File lib/txt_data/format_helpers.rb, line 34
def filter_illegal_characters(value)
  value.tr("-_+$<>:;?!=[]`^|\\'\"`~", "")
end
money_format(value, length:, just: :right, pad: '0') click to toggle source

Right justified, “0” padded, 2 decimal places, with no separator. @param [Fixnum] value @param [Fixnum] length

# File lib/txt_data/format_helpers.rb, line 7
def money_format(value, length:, just: :right, pad: '0')
  txt = ("%.2f" % value.round(2)).to_s.sub(".", "").truncate(length, omission: "")
  justify(txt, length, just, pad)
end
number_format(value, length:, just: :right, pad: '0') click to toggle source

Right justified, “0” padded, no decimal places, with no separator. @param [Fixnum] value @param [Fixnum] length @param [Symbol] just @param [String] pad

# File lib/txt_data/format_helpers.rb, line 17
def number_format(value, length:, just: :right, pad: '0')
  txt = value.to_i.to_s.truncate(length, omission: "")
  justify(txt, length, just, pad)
end
text_format(value, length:, just: :left, sanitize:, pad: ' ') click to toggle source

Left justified, “ ” padded, text. @param [String] value @param [Fixnum] length @param [Symbol] just @param [String] pad

# File lib/txt_data/format_helpers.rb, line 27
def text_format(value, length:, just: :left, sanitize:, pad: ' ')
  txt = sanitize ? filter_illegal_characters(value.to_s).truncate(length, omission: "") : value
  justify(txt, length, just, pad)
end

Private Instance Methods

justify(txt, length, just, pad) click to toggle source
# File lib/txt_data/format_helpers.rb, line 40
def justify(txt, length, just, pad)
  case just
  when :left
    txt.ljust(length, pad)
  when :right
    txt.rjust(length, pad)
  else
    raise ArgumentError, "Justification #{just} is not supported."
  end
end