Class: UKPostcode

Inherits:
Object
  • Object
show all
Defined in:
lib/uk_postcode.rb,
lib/uk_postcode/version.rb

Constant Summary collapse

MATCH =
/\A \s* (?:
  ( G[I1]R \s* [0O]AA )           # special postcode
|
  ( [A-PR-UWYZ01][A-Z01]? )       # area
  ( [0-9IO][0-9A-HJKMNPR-YIO]? )  # district
  (?: \s*
    ( [0-9IO] )                   # sector
    ( [ABD-HJLNPQ-Z10]{2} )       # unit
  )?
) \s* \Z/x
VERSION =
"1.0.0"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(postcode_as_string) ⇒ UKPostcode

Initialise a new UKPostcode instance from the given postcode string



17
18
19
# File 'lib/uk_postcode.rb', line 17

def initialize(postcode_as_string)
  @raw = postcode_as_string
end

Instance Attribute Details

#rawObject (readonly) Also known as: to_s, to_str

Returns the value of attribute raw.



13
14
15
# File 'lib/uk_postcode.rb', line 13

def raw
  @raw
end

Instance Method Details

#areaObject

The first part of the outcode, e.g. W1A 2AB -> W



47
48
49
# File 'lib/uk_postcode.rb', line 47

def area
  parts[0]
end

#districtObject

The second part of the outcode, e.g. W1A 2AB -> 1A



53
54
55
# File 'lib/uk_postcode.rb', line 53

def district
  parts[1]
end

#full?Boolean

Returns true if the postcode is a valid full postcode (e.g. W1A 1AA)

Returns:

  • (Boolean)


29
30
31
# File 'lib/uk_postcode.rb', line 29

def full?
  !!(outcode && incode)
end

#incodeObject

The right-hand part of the postcode, e.g. W1A 1AA -> 1AA



41
42
43
# File 'lib/uk_postcode.rb', line 41

def incode
  sector && unit && [sector, unit].join
end

#inspect(*args) ⇒ Object



81
82
83
# File 'lib/uk_postcode.rb', line 81

def inspect(*args)
  "<#{self.class.to_s} #{raw}>"
end

#normObject Also known as: normalise, normalize

Render the postcode as a normalised string, i.e. in upper case and with spacing. Returns an empty string if the postcode is not valid.



72
73
74
# File 'lib/uk_postcode.rb', line 72

def norm
  [outcode, incode].compact.join(" ")
end

#outcodeObject

The left-hand part of the postcode, e.g. W1A 1AA -> W1A



35
36
37
# File 'lib/uk_postcode.rb', line 35

def outcode
  area && district && [area, district].join
end

#sectorObject

The first part of the incode, e.g. W1A 2AB -> 2



59
60
61
# File 'lib/uk_postcode.rb', line 59

def sector
  parts[2]
end

#unitObject

The second part of the incode, e.g. W1A 2AB -> AB



65
66
67
# File 'lib/uk_postcode.rb', line 65

def unit
  parts[3]
end

#valid?Boolean

Returns true if the postcode is a valid full postcode (e.g. W1A 1AA) or outcode (e.g. W1A)

Returns:

  • (Boolean)


23
24
25
# File 'lib/uk_postcode.rb', line 23

def valid?
  !!outcode
end