class UKPostcode::GeographicPostcode
GeographicPostcode
models the majority of postcodes, containing an area, a district, a sector, and a unit.
Despite the name, it also handles non-geographic postcodes that follow the geographic format.
Constants
- PATTERN
Attributes
Public Class Methods
Initialise a new GeographicPostcode
instance with the given area, district, sector, and unit. Only area is required.
# File lib/uk_postcode/geographic_postcode.rb, line 36 def initialize(area, district = nil, sector = nil, unit = nil) @area = letters(area) @district = digits(district) @sector = digits(sector) @unit = letters(unit) end
Attempts to parse the postcode given in str, and returns an instance of GeographicPostcode
on success, or nil on failure.
# File lib/uk_postcode/geographic_postcode.rb, line 24 def self.parse(str) matched = PATTERN.match(str.strip) if matched new(*(1..4).map { |i| matched[i] }) else nil end end
Public Instance Methods
Find the country associated with the postcode. Possible values are :england, :scotland, :wales, :northern_ireland, :isle_of_man, :channel_islands, or :unknown.
Note that, due to limitations in the underlying data, the country might not always be correct in border regions.
# File lib/uk_postcode/geographic_postcode.rb, line 84 def country CountryFinder.country(self) end
Returns true if the postcode is a valid full postcode (e.g. W1A 1AA)
# File lib/uk_postcode/geographic_postcode.rb, line 67 def full? [area, district, sector, unit].all? end
The right-hand part of the postcode, e.g. W1A 1AA -> 1AA
# File lib/uk_postcode/geographic_postcode.rb, line 54 def incode return nil unless sector && unit [sector, unit].join('') end
The left-hand part of the postcode, e.g. W1A 1AA -> W1A
# File lib/uk_postcode/geographic_postcode.rb, line 47 def outcode return nil unless district [area, district].join('') end
Returns the canonical string representation of the postcode.
# File lib/uk_postcode/geographic_postcode.rb, line 61 def to_s [area, district, " ", sector, unit].compact.join('').strip end
Any geographic postcode is assumed to be valid
# File lib/uk_postcode/geographic_postcode.rb, line 73 def valid? true end
Private Instance Methods
# File lib/uk_postcode/geographic_postcode.rb, line 95 def digits(str) return nil unless str str.upcase.tr("IO", "10") end
# File lib/uk_postcode/geographic_postcode.rb, line 90 def letters(str) return nil unless str str.upcase.tr("10", "IO") end