Class: FixedWidth::Column

Inherits:
Object
  • Object
show all
Defined in:
lib/fixed_width/column.rb

Constant Summary collapse

DEFAULT_PADDING =
' '
DEFAULT_ALIGNMENT =
:right
DEFAULT_TRUNCATE =
false
DEFAULT_FORMATTER =
:to_s

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, length, options = {}) ⇒ Column

Returns a new instance of Column.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/fixed_width/column.rb', line 10

def initialize(name, length, options={})
  assert_valid_options(options)
  @name      = name
  @length    = length
  @alignment = options[:align]    || DEFAULT_ALIGNMENT
  @padding   = options[:padding]  || DEFAULT_PADDING
  @truncate  = options[:truncate] || DEFAULT_TRUNCATE

  @group     = options[:group]

  @unpacker  = "A#{@length}"

  @parser    = options[:parser]
  @parser    ||= case @alignment
             when :right then :lstrip
             when :left  then :rstrip
             end
  @parser    = @parser.to_proc if @parser.is_a?(Symbol)

  @formatter = options[:formatter]
  @formatter ||= DEFAULT_FORMATTER
  @formatter = @formatter.to_proc if @formatter.is_a?(Symbol)

  @nil_blank = options[:nil_blank]
end

Instance Attribute Details

#alignmentObject (readonly)

Returns the value of attribute alignment.



8
9
10
# File 'lib/fixed_width/column.rb', line 8

def alignment
  @alignment
end

#groupObject (readonly)

Returns the value of attribute group.



8
9
10
# File 'lib/fixed_width/column.rb', line 8

def group
  @group
end

#lengthObject (readonly)

Returns the value of attribute length.



8
9
10
# File 'lib/fixed_width/column.rb', line 8

def length
  @length
end

#nameObject (readonly)

Returns the value of attribute name.



8
9
10
# File 'lib/fixed_width/column.rb', line 8

def name
  @name
end

#paddingObject (readonly)

Returns the value of attribute padding.



8
9
10
# File 'lib/fixed_width/column.rb', line 8

def padding
  @padding
end

#truncateObject (readonly)

Returns the value of attribute truncate.



8
9
10
# File 'lib/fixed_width/column.rb', line 8

def truncate
  @truncate
end

#unpackerObject (readonly)

Returns the value of attribute unpacker.



8
9
10
# File 'lib/fixed_width/column.rb', line 8

def unpacker
  @unpacker
end

Instance Method Details

#format(value) ⇒ Object



46
47
48
49
50
51
52
# File 'lib/fixed_width/column.rb', line 46

def format(value)
  pad(
    validate_size(
      @formatter.call(value)
    )
  )
end

#parse(value) ⇒ Object



36
37
38
39
40
41
42
43
44
# File 'lib/fixed_width/column.rb', line 36

def parse(value)
  if @nil_blank && blank?(value)
    return nil
  else
    @parser.call(value)
  end
rescue
  raise ParserError.new("The value '#{value}' could not be parsed: #{$!}")
end