Class: JpZipCode::Filer

Inherits:
Object
  • Object
show all
Defined in:
lib/jp_zip_code/filer.rb

Instance Method Summary collapse

Constructor Details

#initialize(type) ⇒ Filer

Returns a new instance of Filer.



9
10
11
# File 'lib/jp_zip_code/filer.rb', line 9

def initialize(type)
  @type = type.to_sym
end

Instance Method Details

#cleanObject



89
90
91
# File 'lib/jp_zip_code/filer.rb', line 89

def clean
  File.delete(zip_file_name) if File.exist?(zip_file_name)
end

#download_fileObject



31
32
33
34
35
36
37
# File 'lib/jp_zip_code/filer.rb', line 31

def download_file
  open(zip_file_name, 'wb') do |file|
    open(download_url) do |data|
      file.write(data.read)
    end
  end
end

#download_urlObject



13
14
15
16
17
18
19
20
# File 'lib/jp_zip_code/filer.rb', line 13

def download_url
  case @type
  when :jp
    'https://www.post.japanpost.jp/zipcode/dl/kogaki/zip/ken_all.zip'
  when :roman
    'https://www.post.japanpost.jp/zipcode/dl/roman/ken_all_rome.zip'
  end
end

#fetch_dataObject



22
23
24
25
# File 'lib/jp_zip_code/filer.rb', line 22

def fetch_data
  download_file
  unzip_file_and_get_data
end

#get_row(file) ⇒ Object



58
59
60
# File 'lib/jp_zip_code/filer.rb', line 58

def get_row(file)
  file.get_input_stream.read.encode('utf-8', 'cp932').delete('"').split("\n")
end

#to_hash(datas) ⇒ Object



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/jp_zip_code/filer.rb', line 62

def to_hash(datas)
  case @type
  when :jp
    {
      code: datas[0],
      old_zip_code: datas[1],
      zip_code: datas[2],
      pref_kana: datas[3],
      city_kana: datas[4],
      town_kana: datas[5],
      pref_kanji: datas[6],
      city_kanji: datas[7],
      town_kanji: datas[8]
    }
  when :roman
    {
      zip_code: datas[0],
      pref_kanji: datas[1],
      city_kanji: datas[2],
      town_kanji: datas[3],
      pref_roman: datas[4],
      city_roman: datas[5],
      town_roman: datas[6]
    }
  end
end

#unzip(file_name) ⇒ Object



50
51
52
53
54
55
56
# File 'lib/jp_zip_code/filer.rb', line 50

def unzip(file_name)
  Zip::File.open(file_name) do |csv_files|
    csv_files.each do |file|
      yield(file)
    end
  end
end

#unzip_file_and_get_dataObject



39
40
41
42
43
44
45
46
47
48
# File 'lib/jp_zip_code/filer.rb', line 39

def unzip_file_and_get_data
  hash = {}
  unzip(zip_file_name) do |file|
    get_row(file).each do |row|
      row_data = to_hash(row.split(',').map(&:strip))
      hash[row_data[:zip_code]] = row_data
    end
  end
  hash
end

#zip_file_nameObject



27
28
29
# File 'lib/jp_zip_code/filer.rb', line 27

def zip_file_name
  File.basename(download_url)
end