Module: Firstclasspostcodes::Operations::Methods::FormatAddress

Defined in:
lib/firstclasspostcodes/operations/methods/format_address.rb

Instance Method Summary collapse

Instance Method Details

#format_address(index) ⇒ Object

Raises:

  • (StandardError)


7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/firstclasspostcodes/operations/methods/format_address.rb', line 7

def format_address(index)
  type, element = index.split(":")

  data = {
    locality: self[:city] || self[:locality],
    region: self[:county] || self[:region],
    postcode: self[:postcode],
    country: self[:country],
  }

  return data if type == "postcode"

  list = self[type.to_sym]

  index = element.to_i

  raise StandardError, `Received index "#{index}" but no #{type} data.` if list.empty?

  address = if type == "numbers"
              component = list[index]
              join = ->(*args) { args.compact.reject(&:empty?).join(", ") }
              join.call(component[:number], component[:building], component[:street])
            else
              list[index]
            end

  data.merge(address: address)
end