Class: Phony::LocalSplitters::Fixed

Inherits:
Object
  • Object
show all
Defined in:
lib/phony/local_splitters/fixed.rb

Overview

Local splitter class to split the last part of a number, i.e. minus cc or ndc.

Countries can create new instances according to their needs.

Note: Countries should use instance_for

to avoid getting new local splitter instances.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(format = nil) ⇒ Fixed

Initialize with a local format, like [3, 2, 2] (also the default).

The format [3, 2, 2] splits a number like ‘3332222’ into [‘333’, ‘22’, ‘22’].



29
30
31
32
33
# File 'lib/phony/local_splitters/fixed.rb', line 29

def initialize format = nil
  format = format && format.dup || [3, 2, 2]
  @format, @length = extract_params format
  @format << @format.pop + 10
end

Class Method Details

.instance_for(format = nil) ⇒ Object

Get a splitter for the given format.

Caches the created splitter for the given format.



21
22
23
# File 'lib/phony/local_splitters/fixed.rb', line 21

def self.instance_for format = nil
  @mapping[format] ||= new(format)
end

Instance Method Details

#extract_params(format) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
# File 'lib/phony/local_splitters/fixed.rb', line 37

def extract_params format
  if format.last.respond_to? :max
    last = format.pop
    length = format.inject(0) { |total, part| total + part }
    length = (length+last.min..length+last.max)
    format << last.min
  else
    length = format.inject(0) { |total, part| total + part }
  end
  [format, length]
end

#plausible?(rest, hints = {}) ⇒ Boolean

Returns:

  • (Boolean)


64
65
66
67
68
# File 'lib/phony/local_splitters/fixed.rb', line 64

def plausible? rest, hints = {}
  return true if hints[:check_length] == false
  
  @length === rest.inject(0) { |total, part| total + part.size }
end

#split(number) ⇒ Object

Split a local number according to an assumed country specific format.

Examples

  • split ‘3643533’ # => [‘364’, ‘35’, ‘33’] # (Switzerland)



54
55
56
57
58
59
60
# File 'lib/phony/local_splitters/fixed.rb', line 54

def split number
  @format.inject([]) do |result, size|
    result << number.slice!(0..size-1)
    return result if number.empty?
    result
  end
end