aboutsummaryrefslogtreecommitdiffstats
path: root/lib/norwegian-postcodes.rb
blob: be77c8eb7f8ebf5750f1ef157d7e2b34ed1e44c9 (plain) (blame)
1
2
3
4
5
6
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
module PostCodes

  require 'norwegian-postcodes/railtie' if defined?(Rails)

  Counties = [
    "ØSTFOLD",
    "AKERSHUS",
    "OSLO",
    "HEDMARK",
    "OPPLAND",
    "BUSKERUD",
    "VESTFOLD",
    "TELEMARK",
    "AUST-AGDER",
    "VEST-AGDER",
    "ROGALAND",
    "HORDALAND",
    "(BERGEN)",
    "SOGN OG FJORDANE",
    "MØRE OG ROMSDAL",
    "SØR-TRØNDELAG",
    "NORD-TRØNDELAG",
    "NORDLAND",
    "TROMS",
    "FINNMARK",
    "SVALBARD",
    "JAN MAYEN",
    "KONTINENTALSOKKELEN"
  ]

  class PostCode
    attr_reader :postcode, :city, :municipality, :municipality_name, :cat

    def initialize(postcode, city, muni, muni_name, cat)
      @postcode, @city, @municipality, @municipality_name, @cat = postcode, city, muni, muni_name, cat
    end

    def county
      code = @municipality[0..1].to_i
      [code, PostCodes.county(code)]
    end

    def to_s
      [@postcode, @city, @municipality, @municipality_name, @cat].join("\t")
    end
  end

  class << self
    def load(file)
      @postcodes = []
      if file.is_a?(String)
        f = File.open(file, :encoding => Encoding::ISO_8859_15)
      else
        f = file
      end

      f.each_line do |l|
        a = l.chomp().split("\t").map{|s| s.encode(Encoding::UTF_8)}
        @postcodes << PostCode.new(*a)
      end
    end

    def search(pc)
      res = @postcodes.bsearch {|x| x.postcode.to_i >= pc.to_i}
      unless res.nil?
        res.postcode.to_i == pc.to_i ? res : nil
      end
    end

    def county(c)
      return nil unless c > 0 && c <= Counties.size
      Counties[c - 1]
    end
  end
end