Class: FixedWidthStructure

Inherits:
Object
  • Object
show all
Defined in:
lib/fixed-width-structures.rb,
lib/fixed-width-structures/version.rb

Constant Summary collapse

VERSION =
"0.9.0"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.add_attribute(attribute, type, size, default_value = nil) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/fixed-width-structures.rb', line 3

def self.add_attribute( attribute, type, size, default_value = nil )
  @attributes ||= {}
  @attributes[ attribute.to_sym ] = {
    :type => type,
    :size => size,
    :position => self.size
  }
  increment_size( size )
  if default_value
    define_method attribute do
      value = instance_variable_get( "@#{attribute}" )
      value ? value : default_value
    end
    attr_writer attribute.to_sym
  else
    attr_accessor attribute.to_sym
  end
end

.alphabetic(attribute, length, default_value = '') ⇒ Object



34
35
36
# File 'lib/fixed-width-structures.rb', line 34

def self.alphabetic( attribute, length, default_value = '' )
  add_attribute( attribute, "%-#{length}.#{length}s", length, default_value )
end

.attributesObject



22
23
24
# File 'lib/fixed-width-structures.rb', line 22

def self.attributes
  @attributes ||= {}
end

.filler(length, character = 'X') ⇒ Object



42
43
44
# File 'lib/fixed-width-structures.rb', line 42

def self.filler( length, character = 'X' )
  alphabetic( "filler_#{size}".to_sym, length, character*length )
end

.increment_size(increment) ⇒ Object



30
31
32
# File 'lib/fixed-width-structures.rb', line 30

def self.increment_size( increment )
  @size = self.size + increment
end

.numeric(attribute, length, default_value = 0) ⇒ Object



38
39
40
# File 'lib/fixed-width-structures.rb', line 38

def self.numeric( attribute, length, default_value = 0 )
  add_attribute( attribute, "%#{length}.#{length}d", length, default_value )
end

.sizeObject



26
27
28
# File 'lib/fixed-width-structures.rb', line 26

def self.size
  @size ||= 0
end

.space(length) ⇒ Object



46
47
48
# File 'lib/fixed-width-structures.rb', line 46

def self.space( length )
  filler( length, ' ' )
end

Instance Method Details

#to_sObject



50
51
52
53
54
55
# File 'lib/fixed-width-structures.rb', line 50

def to_s
  self.class.attributes.to_a.sort{|a,b|a.last[:position]<=>b.last[:position]}.inject('') do |result,current|
    this = current.last[ :type ]%send(current.first)
    result << "%-#{current.last[:size]}.#{current.last[:size]}s"%this
  end
end