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.0.1"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.add_attribute(attribute, type, size) ⇒ Object



3
4
5
6
7
8
9
10
11
12
# File 'lib/fixed-width-structures.rb', line 3

def self.add_attribute( attribute, type, size )
  @attributes ||= {}
  @attributes[ attribute.to_sym ] = {
    :type => type,
    :size => size,
    :position => self.size
  }
  increment_size( size )
  attr_accessor attribute.to_sym
end

.alphabetic(attribute, length) ⇒ Object



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

def self.alphabetic( attribute, length )
  add_attribute( attribute, "%-#{length}.#{length}s", length )
  define_method attribute do
    value = instance_variable_get( "@#{attribute}" )
    value ? value : ''
  end
end

.attributesObject



14
15
16
# File 'lib/fixed-width-structures.rb', line 14

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

.increment_size(increment) ⇒ Object



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

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

.numeric(attribute, length) ⇒ Object



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

def self.numeric( attribute, length )
  add_attribute( attribute, "%#{length}.#{length}d", length )
  define_method attribute do
    value = instance_variable_get( "@#{attribute}" )
    value ? value : 0
  end
end

.sizeObject



18
19
20
# File 'lib/fixed-width-structures.rb', line 18

def self.size
  @size ||= 0
end

Instance Method Details

#to_sObject



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

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