Skip to content

Commit

Permalink
Add Faker::Vehicle.singapore_license_plate (#1410)
Browse files Browse the repository at this point in the history
* Add Singapore vehicle license plate

* Update en-SG.yml
  • Loading branch information
anonoz authored and vbrazo committed Oct 18, 2018
1 parent 069817e commit 8b7e160
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 1 deletion.
5 changes: 4 additions & 1 deletion doc/vehicle.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,10 @@ Faker::Vehicle.mileage(50_000) #=> 81557
Faker::Vehicle.mileage(50_000, 250_000) #=> 117503
Faker::Vehicle.kilometrage #=> 35378

# Random vehicle license plate
# Random vehicle license plate (USA by default)
Faker::Vehicle.license_plate #=> "DEP-2483"
Faker::Vehicle.license_plate('FL') #=> "977 UNU"

# Random vehicle license plate for Singapore (if locale is set)
Faker::Vehicle.singapore_license_plate #=> "SLV1854M"
```
19 changes: 19 additions & 0 deletions lib/faker/vehicle.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ class Vehicle < Base
VIN_MAP = '0123456789X'
VIN_WEIGHTS = '8765432X098765432'
VIN_REGEX = /^[A-Z0-9]{3}[A-Z0-9]{5}[A-Z0-9]{1}[A-Z0-9]{1}[A-Z0-0]{1}[A-Z0-9]{1}\d{5}$/
SG_CHECKSUM_WEIGHTS = [3, 14, 2, 12, 2, 11, 1].freeze
SG_CHECKSUM_CHARS = 'AYUSPLJGDBZXTRMKHEC'

class << self
def vin
Expand Down Expand Up @@ -96,6 +98,12 @@ def license_plate(state_abreviation = '')
regexify(bothify(fetch(key)))
end

def singapore_license_plate
key = 'vehicle.license_plate'
plate_number = regexify(bothify(fetch(key)))
"#{plate_number}#{singapore_checksum(plate_number)}"
end

private

def first_eight(number)
Expand Down Expand Up @@ -125,6 +133,17 @@ def vin_char_to_number(char)

VIN_MAP[index]
end

def singapore_checksum(plate_number)
padded_alphabets = format('%3s', plate_number[/^[A-Z]+/]).tr(' ', '-').split('')
padded_digits = format('%04d', plate_number[/\d+/]).split('').map(&:to_i)
sum = [*padded_alphabets, *padded_digits].each_with_index.reduce(0) do |memo, (char, i)|
value = char.is_a?(Integer) ? char : char.ord - 64
memo + (SG_CHECKSUM_WEIGHTS[i] * value)
end

SG_CHECKSUM_CHARS.split('')[sum % 19]
end
end
end
end
2 changes: 2 additions & 0 deletions lib/locales/en-SG.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,5 @@ en-SG:
default_country: [Singapore]
phone_number:
formats: ['+65 6### ####', '+65 9### ####', '+65 8### ####']
vehicle:
license_plate: 'S??####'
4 changes: 4 additions & 0 deletions test/test_en_sg_locale.rb
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,8 @@ def test_en_sg_name_methods
assert Faker::Name.first_name.is_a? String
assert Faker::Name.name.is_a? String
end

def test_singapore_license_plate
assert_match(/^S[A-Z]{2}\d{1,4}[A-Z]{1}$/, Faker::Vehicle.singapore_license_plate)
end
end

0 comments on commit 8b7e160

Please sign in to comment.