Module: Jipcode::JapanPost

Defined in:
lib/jipcode/japan_post.rb

Constant Summary collapse

ZIPCODE_URLS =
{
  general: 'https://www.post.japanpost.jp/zipcode/dl/kogaki/zip/ken_all.zip'.freeze,
  company: 'https://www.post.japanpost.jp/zipcode/dl/jigyosyo/zip/jigyosyo.zip'.freeze
}.freeze
ZIPCODE_FILES =
{
  general: 'KEN_ALL.CSV'.freeze,
  company: 'JIGYOSYO.CSV'.freeze
}.freeze

Class Method Summary collapse

Class Method Details

.download_allObject



26
27
28
29
30
31
32
33
34
# File 'lib/jipcode/japan_post.rb', line 26

def download_all
  ZIPCODE_URLS.each do |type, url|
    url = URI.parse(url)
    http = Net::HTTP.new(url.host, 443)
    http.use_ssl = true
    res = http.get(url.path)
    File.open("zipcode/#{type}.zip", 'wb') { |f| f.write(res.body) }
  end
end

.import_allObject



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
76
77
78
79
80
# File 'lib/jipcode/japan_post.rb', line 36

def import_all
  File.rename(ZIPCODE_PATH, 'zipcode/previous') if File.exist?(ZIPCODE_PATH)
  Dir.mkdir(ZIPCODE_PATH)

  # 事業所のデータには都道府県、市区町村、町域、番地のカナが与えられていない
  # そのため、郵便番号情報から、都道府県、市区町村、町域のカナ読みを持っていきたいため、hashに保存しておく
  kana_dict = Hash.new ""

  zipcodes = unpack(:general)
  import(zipcodes) do |row|
    zipcode    = row[2] # 郵便番号
    prefecture = row[6] # 都道府県
    city       = row[7] # 市区町村
    town       = row[8] # 町域

    prefecture_kana = row[3] # 都道府県カナ
    city_kana       = row[4] # 市区町村カナ
    town_kana       = row[5] # 町域カナ

    kana_dict[prefecture] = prefecture_kana
    kana_dict[city]       = city_kana

    [zipcode, prefecture, city, town, prefecture_kana, city_kana, town_kana]
  end

  zipcodes = unpack(:company)
  import(zipcodes) do |row|
    zipcode    = row[7] # 郵便番号
    prefecture = row[3] # 都道府県
    city       = row[4] # 市区町村
    town       = row[5] + row[6] # 町域 + 番地

    prefecture_kana = kana_dict[prefecture]
    city_kana       = kana_dict[city]
    town_kana       = "" # [MEMO] 事業所データの町域番地に対してのカナは提供しない

    [zipcode, prefecture, city, town, prefecture_kana, city_kana, town_kana]
  end

  FileUtils.rm_rf('zipcode/previous')
rescue => e
  FileUtils.rm_rf(ZIPCODE_PATH)
  File.rename('zipcode/previous', ZIPCODE_PATH) if File.exist?('zipcode/previous')
  raise e, '日本郵便のデータを読み込めませんでした。'
end

.updateObject



18
19
20
21
22
23
24
# File 'lib/jipcode/japan_post.rb', line 18

def update
  download_all
  import_all

  # データの更新月を記録する
  File.open('zipcode/current_month', 'w') { |f| f.write(Time.now.strftime('%Y%m')) }
end