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

area[R]
district[R]
sector[R]
unit[R]

Public Class Methods

new(area, district = nil, sector = nil, unit = nil) click to toggle source

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
parse(str) click to toggle source

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

country() click to toggle source

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
full?() click to toggle source

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
incode() click to toggle source

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
outcode() click to toggle source

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
to_s() click to toggle source

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
valid?() click to toggle source

Any geographic postcode is assumed to be valid

# File lib/uk_postcode/geographic_postcode.rb, line 73
def valid?
  true
end

Private Instance Methods

digits(str) click to toggle source
# File lib/uk_postcode/geographic_postcode.rb, line 95
def digits(str)
  return nil unless str
  str.upcase.tr("IO", "10")
end
letters(str) click to toggle source
# File lib/uk_postcode/geographic_postcode.rb, line 90
def letters(str)
  return nil unless str
  str.upcase.tr("10", "IO")
end