Module: Jipcode::JapanPost

Defined in:
lib/jipcode/japan_post.rb

Constant Summary collapse

ZIPCODE_URLS =
{
  general: 'http://www.post.japanpost.jp/zipcode/dl/kogaki/zip/ken_all.zip'.freeze,
  company: 'http://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



23
24
25
26
27
28
29
30
31
# File 'lib/jipcode/japan_post.rb', line 23

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

.import_allObject



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
# File 'lib/jipcode/japan_post.rb', line 33

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

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

    [zipcode, prefecture, city, town]
  end

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

    [zipcode, prefecture, city, town]
  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
# File 'lib/jipcode/japan_post.rb', line 18

def update
  download_all
  import_all
end