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.



7
8
9
# File 'lib/jp_zip_code/filer.rb', line 7

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

Instance Method Details

#cleanObject



87
88
89
# File 'lib/jp_zip_code/filer.rb', line 87

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

#download_fileObject



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

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

#download_urlObject



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

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

#fetch_dataObject



20
21
22
23
# File 'lib/jp_zip_code/filer.rb', line 20

def fetch_data
  download_file
  unzip_file_and_get_data
end

#get_row(file) ⇒ Object



56
57
58
# File 'lib/jp_zip_code/filer.rb', line 56

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

#to_hash(datas) ⇒ Object



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

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



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

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



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

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



25
26
27
# File 'lib/jp_zip_code/filer.rb', line 25

def zip_file_name
  File.basename(download_url)
end