Class: Fencer::Base

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

Constant Summary collapse

Converters =
{
  string:  -> s { s.to_s.strip },
  integer: -> s { s.to_i },
  decimal: -> s { s.nil? ? nil : BigDecimal(s) },
}

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(raw_data, delimiter = nil) ⇒ Base

Returns a new instance of Base.



50
51
52
53
54
55
56
# File 'lib/fencer.rb', line 50

def initialize(raw_data, delimiter = nil)
  @values    = {}
  @delimiter = delimiter
  @raw_data  = raw_data

  parse!
end

Class Attribute Details

.fieldsObject (readonly)

Returns the value of attribute fields.



13
14
15
# File 'lib/fencer.rb', line 13

def fields
  @fields
end

Class Method Details

.decimal(name, size) ⇒ Object



45
46
47
# File 'lib/fencer.rb', line 45

def decimal(name, size)
  field(name, size, :decimal)
end

.field(name, size, convert = nil) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/fencer.rb', line 19

def field(name, size, convert = nil)
  # error handling, ahoy!
  raise "#{name} already defined as a field on #{self.name}" if fields.has_key?(name)

  unless convert.nil? || Converters.has_key?(convert) || convert.is_a?(Proc)
    raise "Invalid converter"
  end

  fields[name] = { size: size, convert: convert }

  # create our attr method
  define_method(name) { @values[name] }
end

.inherited(subclass) ⇒ Object



15
16
17
# File 'lib/fencer.rb', line 15

def inherited(subclass)
  subclass.instance_variable_set(:@fields, {})
end

.integer(name, size) ⇒ Object



41
42
43
# File 'lib/fencer.rb', line 41

def integer(name, size)
  field(name, size, :integer)
end

.space(size) ⇒ Object



33
34
35
# File 'lib/fencer.rb', line 33

def space(size)
  fields[:"_#{fields.length.succ}"] = { size: size, space: true }
end

.string(name, size) ⇒ Object



37
38
39
# File 'lib/fencer.rb', line 37

def string(name, size)
  field(name, size, :string)
end

Instance Method Details

#to_hashObject



58
59
60
# File 'lib/fencer.rb', line 58

def to_hash
  @values
end