Class: Magnet::Parser

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

Defined Under Namespace

Classes: InvalidDataError

Constant Summary collapse

TRACKS =
{
  1 => /\A%(?<format>[A-Z])(?<pan>[0-9]{1,19})\^(?<name>[A-Za-z.\/ ]{2,26})\^(?<expiration>\d{4}|\^)(?<service_code>\d{3}|\^)(?<discretionary_data>[^\?]+)\?\Z/,
  2 => /\A;(?<format>[A-Z])(?<pan>[0-9]{1,19})=(?<expiration>\d{4}|=)(?<service_code>\d{3}|=)(?<discretionary_data>[^\?]+)\?\Z/
}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(track = :auto) ⇒ Parser

Returns a new instance of Parser.



8
9
10
# File 'lib/magnet/parser.rb', line 8

def initialize(track = :auto)
  @track = :auto
end

Instance Method Details

#parse(track_data) ⇒ Object

Raises:



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/magnet/parser.rb', line 12

def parse(track_data)
  tracks = @track == :auto ? TRACKS.values : [TRACKS[@track]]

  tracks.each do |track|
    if m = track.match(track_data)
      attributes = {}
      attributes[:format] = m[:format]
      attributes[:pan] = m[:pan]
      attributes[:name] = m[:name]
      attributes[:expiration] = m[:expiration] == "^" ? nil : m[:expiration]
      attributes[:service_code] = m[:service_code] == "^" ? nil : m[:service_code]
      attributes[:discretionary_data] = m[:discretionary_data]
      return attributes
    end
  end

  raise InvalidDataError, "track data is not valid"
end