Ruby で自家製スクリプトを書く 08

読み込んだ CSV を保存する SQL ファイル名でそのまま保存する

csv2sql.rb

#!/bin/env ruby
$KCODE='utf8'

require 'yaml'
require 'kconv'
require 'rubygems'
require 'fastercsv'

config_file = 'config.yaml'
configs = YAML.load_file(config_file)

def convert_char_encoding(encoding, data)
  begin
    case encoding
      when 'jis'
        return Kconv.tojis(data)
      when 'Shfit-JIS'
        return Kconv.tosjis(data)
      when 'EUC-JP'
        return Kconv.toeuc(data)
      when 'UTF-8'
        return Kconv.toutf8(data)
      else
        exit(1)
    end
  rescue SystemExit => e
    p 'set invalid charcter encoding or nil.'
    exit(0)
  end
end

# ファイル名に日付を付加する
day = Time.now
current_time = day.strftime("%Y%m%d_%H%M%S") #=> "20080522_160322"

fp = File.open(current_time + configs['filename']['sql'], 'w+')

FasterCSV.foreach(configs['filename']['csv'], {:col_sep => configs['csv']['fs'], :quote_char => configs['csv']['quote'], :headers => configs['csv']['headers']}) do |row|
  p row #=> 配列の構成
  line = []
  row.each do |column|
    if (configs['encoding']['input'] == configs['encoding']['output'])
      line.push column #=> 要素の構成
    else
      line.push convert_char_encoding(configs['encoding']['output'], column) #=> 要素の構成
    end
  end
  fp.puts line.join("\t") + "\n"
end
fp.close

実行結果。

% ruby csv2sql.rb
["1", "myname", "myaddress", "123-4567"]
["2", "yourname", "youraddress", "890-1234"]
["3", "hisname", "hisaddress", ""]
["4", "hername", "heraddress", "A56-7890"]
% ls 
20080525_161027sample.sql csv2sql.rb                read_yaml.rb
config.yaml               openfile.rb               sample.csv
% cat 20080525_161027sample.sql 
1       myname  myaddress       123-4567
2       yourname        youraddress     890-1234
3       hisname hisaddress
4       hername heraddress      A56-7890