Class: JLG::Governments

Inherits:
Object
  • Object
show all
Includes:
DATA
Defined in:
lib/japanese_local_governments/governments.rb

Constant Summary

Constants included from DATA

DATA::GOV_DATA, DATA::GOV_DATA_NAME_INDEX, DATA::HEADER

Class Method Summary collapse

Class Method Details

.append_code(inputfile, outputfile = nil, pref: 'pref', name: 'name', sjis: false) ⇒ Object

都道府県名、自治体名を持つCSVファイルを読み込み 自治体コードを付加する

Parameters:

  • inputfile (String)

    自治体コードを付加したいCSVファイル

  • outputfile (String) (defaults to: nil)

    出力ファイル名。

  • pref (String) (defaults to: 'pref')

    都道府県カラムの名前

  • name (String) (defaults to: 'name')

    自治体名カラムの名前

  • sjis (Boolean) (defaults to: false)

    処理したいファイルがShift_JISの場合、trueをセット。デフォルトはfalseでUTF-8として処理する



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/japanese_local_governments/governments.rb', line 43

def self.append_code(inputfile, outputfile=nil, pref:'pref', name: 'name',sjis:false)
  encode = (sjis) ? 'Shift_JIS':'UTF-8'
  if outputfile.nil?
    date = Date.today.strftime('%Y%m%d')
    outputfile = './' + File.basename(inputfile,'.*') + "_#{date}.csv"
  end
  CSV.open(inputfile,"r:#{encode}:UTF-8",headers: true,return_headers:true) do|csv|
    CSV.open(outputfile,"wb:#{encode}") do |out|
      csv.each do |row|
        if row.header_row?
          out<<row.headers.to_a.insert(0,'code')
        else
          code = code_of(row[pref],row[name])
          out<<row.to_h.values.insert(0,code)
        end
      end
    end
  end
end

.code_of(pref, name = pref) ⇒ String

都道府県名、自治体名からコードを得る

Parameters:

  • pref (String)

    都道府県名

  • name (String) (defaults to: pref)

    自治体名

Returns:

  • (String)

    自治体コード。6桁。ゼロパディングあり。



25
26
27
28
29
# File 'lib/japanese_local_governments/governments.rb', line 25

def self.code_of(pref, name=pref)
  GOV_DATA[GOV_DATA_NAME_INDEX[pref][name]][:code]
rescue
  nil
end

.data_of(code) ⇒ Object

コードから自治体データを得る

Parameters:

  • code (String)

    自治体コード。6桁。ゼロパディングあり。



33
34
35
# File 'lib/japanese_local_governments/governments.rb', line 33

def self.data_of(code)
  GOV_DATA[code]
end

.list(filename = nil, sjis: false) ⇒ Object

地方自治体のリストを出力する

Parameters:

  • filename (String) (defaults to: nil)

    出力ファイルのパス

  • sjis (Boolean) (defaults to: false)

    Shift_JISで出力する場合に true とする



12
13
14
15
16
17
18
19
# File 'lib/japanese_local_governments/governments.rb', line 12

def self.list(filename=nil,sjis:false)
  JLG.list(filename,sjis:sjis){|out|
    out.puts HEADER.join(',')
    GOV_DATA.values.each do |data|
      out.puts data.values.join(',')
    end
  }
end