-
Notifications
You must be signed in to change notification settings - Fork 24
/
Rakefile
executable file
·65 lines (51 loc) · 1.64 KB
/
Rakefile
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
#!/usr/bin/env rake
# frozen_string_literal: true
require 'bundler/gem_tasks'
desc '郵便番号のデータを作成/更新する'
task :create_zip_code_data do
require 'csv'
require 'jp_prefecture'
file_name = 'ken_all_utf8.csv'
# download files
`curl -O https://www.post.japanpost.jp/zipcode/dl/kogaki/zip/ken_all.zip`
`unzip ken_all.zip`
`iconv -f sjis -t utf-8 ken_all.csv > #{file_name}`
`rm ken_all.zip`
`rm ken_all.csv`
zips = []
# read CSV
CSV.foreach(file_name, headers: false) { |line| zips << [line[2], line[6]] }
# create sorted list of zips -> prefecture_code
zips = zips
.collect { |zip, prefecture| [zip.to_i, JpPrefecture::Prefecture.find(name: prefecture).code] }
.sort { |x, y| x[0] <=> y[0] }
# prepare calculation
ranged_zips = []
current = [zips.first[0], zips.first[0], zips.first[1]]
# calculate the zip ranges of each prefecture
zips.each do |zip, code|
if current[2] == code
current[1] = zip
else
ranged_zips << current
current = [zip, zip, code]
end
end
# add last prefecture
ranged_zips << current
# create prefecture hash
prefectures_to_zip = {}
ranged_zips.each do |r0, r1, code|
prefectures_to_zip[code] ||= []
prefectures_to_zip[code] << [r0, r1]
end
prefectures_to_zip = Hash[*prefectures_to_zip.sort.flatten(1)]
# save result
File.open('data/zip.yml', 'w') do |file|
file.write "# { prefecture_code: [[from_zip_1, to_zip_1], [from_zip_2, to_zip_2], ...], ... }\n"
file.write "# Last updated: #{Time.now.utc}\n"
file.write prefectures_to_zip.to_yaml
end
# delete temporary file
`rm #{file_name}`
end