Class: JpAddress::Zipcode

Inherits:
ApplicationRecord show all
Defined in:
app/models/jp_address/zipcode.rb

Defined Under Namespace

Classes: DownloadError

Constant Summary collapse

MASTER_CSV_PATH =

日本郵便からダウンロードした CSV の一時保存先。

'tmp/ken_all.csv'.freeze
MASTER_FILE_URL =

郵便番号データ(住所の郵便番号/小書き)の配布 URL。

'https://www.post.japanpost.jp/zipcode/dl/kogaki/zip/ken_all.zip'.freeze
INSERT_BATCH_SIZE =

insert_all で一度に流し込む件数。

1_000
MAX_REDIRECTS =

リダイレクトを追う上限。

5

Class Method Summary collapse

Class Method Details

._find_shared_name_from(names) ⇒ Object

引数に渡された地名群から、先頭から見て共通となる地名を返します。

input = %w[鳴子温泉小身川 鳴子温泉川袋 鳴子温泉木戸脇 ]

return => 鳴子温泉

共通部分が1文字しかない場合(例:大分/大阪)は、地名として意味を なさないので空文字を返します。ただし短い方の地名がまるごと共通部分に なる場合(例:東中島/東中島本町)は、その地名をそのまま返します。



175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
# File 'app/models/jp_address/zipcode.rb', line 175

def self._find_shared_name_from(names)
  names = Array(names).reject { |name| name.blank? }
  return '' if names.empty?

  shortest      = names.min_by { |name| name.length }
  shared_length = 0
  shortest.each_char.with_index do |char, pos|
    break unless names.all? { |name| name[pos] == char }

    shared_length = pos + 1
  end

  return shortest if shared_length == shortest.length

  shared_length > 1 ? shortest[0, shared_length] : ''
end

.download_master_file_from_japanpost ⇒ Object



18
19
20
21
22
23
24
25
26
27
# File 'app/models/jp_address/zipcode.rb', line 18

def self.download_master_file_from_japanpost
  _setup_directory
  tmp_zip = _save_zip(_request_to_japanpost)
  begin
    _save_csv(tmp_zip.path)
  ensure
    tmp_zip.close!
  end
  :success if File.exist?(MASTER_CSV_PATH)
end

.load_master_data(csv_path = MASTER_CSV_PATH) ⇒ Object

CSV を読み込んでテーブルを作り直します。

同じ郵便番号を持つ行は1レコードに統合してから insert するので、 郵便番号はテーブル内で一意になります。



81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'app/models/jp_address/zipcode.rb', line 81

def self.load_master_data(csv_path = MASTER_CSV_PATH)
  unless File.exist?(csv_path)
    raise ArgumentError, "#{csv_path} does not exist" unless csv_path == MASTER_CSV_PATH

    download_master_file_from_japanpost
  end

  _clear_table
  transaction do
    _each_record_batch_from(csv_path) { |batch| insert_all!(batch) }
  end
  _remove_csv
  nil
end