Class: Cpr::Field

Inherits:
Object
  • Object
show all
Defined in:
lib/cpr/field.rb

Direct Known Subclasses

AlphanumericField, NumericField

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, range, opts = {}) ⇒ Field

Returns a new instance of Field.



5
6
7
8
9
# File 'lib/cpr/field.rb', line 5

def initialize(name, range, opts = {})
  @name = name
  @range = range
  @default = opts[:default]
end

Instance Attribute Details

#defaultObject (readonly)

Returns the value of attribute default.



4
5
6
# File 'lib/cpr/field.rb', line 4

def default
  @default
end

#nameObject (readonly)

Returns the value of attribute name.



4
5
6
# File 'lib/cpr/field.rb', line 4

def name
  @name
end

#rangeObject (readonly)

Returns the value of attribute range.



4
5
6
# File 'lib/cpr/field.rb', line 4

def range
  @range
end

Class Method Details

.create_type(type, *args) ⇒ Object



40
41
42
43
44
45
46
47
# File 'lib/cpr/field.rb', line 40

def self.create_type(type, *args)
  klass = case type
  when 'A' then AlphanumericField
  when 'N' then NumericField
  else raise "Invalid value for type '#{type}'"
  end
  klass.new(*args)
end

Instance Method Details

#fillObject



20
21
22
23
24
25
26
# File 'lib/cpr/field.rb', line 20

def fill
  if @default != nil
    cast_for_write @default
  else
    " "*length
  end
end

#lengthObject



28
29
30
# File 'lib/cpr/field.rb', line 28

def length
  @range.max - @range.begin + 1
end

#patternObject



32
33
34
35
36
37
38
# File 'lib/cpr/field.rb', line 32

def pattern
  if default
    cast_for_write(default)
  else
    typed_pattern
  end
end

#read(raw) ⇒ Object



11
12
13
# File 'lib/cpr/field.rb', line 11

def read(raw)
  cast_for_read(raw[range])
end

#write(raw, value) ⇒ Object



15
16
17
18
# File 'lib/cpr/field.rb', line 15

def write(raw, value)
  raw[range] = cast_for_write(value).encode(Encoding::ISO_8859_1, undef: :replace, invalid: :replace)[0...length]
  raw
end