Skip to content

Instantly share code, notes, and snippets.

@jiikko
Last active December 29, 2015 02:39
Show Gist options
  • Save jiikko/7601884 to your computer and use it in GitHub Desktop.
Save jiikko/7601884 to your computer and use it in GitHub Desktop.
require 'csv'
def import_spots(model: nil, csv_obj: nil, except_column: nil)
header = csv_obj.shift
csv_obj.each do |row|
record = Hash[header.zip(row)]
next if record["ページ名(名称)"].nil? # 空行を無視する
record.except!(except_column)
spot = model.new
spot.prefecture = Prefecture.find_by(name: record['都道府県']) || raise("都道府県が見つかりません#{record["ページ名(名称)"]}")
spot.title = record["ページ名(名称)"]
city_data = record["市区町村"].gsub(" ","")
spot.city = City.find_or_create_by(name: city_data)
spot.address = record["住所"].sub(Regexp.union(Prefecture.pluck(:name)), "")
tag1 = record["タグ1"].gsub("$$", spot.prefecture.name).sub("$", "")
case model.to_s
when Cremation.to_s
tag1 = record["タグ1"].gsub("$$", spot.prefecture.name).sub("$", "")
tag2 = record["タグ2"].gsub("$$", spot.city.name).sub("$", "")
spot.tag_list = [tag1, tag2, record["タグ3"], record["タグ4"]].join(",")
spot.powered_by = record["設置主体"]
when TaxOffice.to_s
tag1 = record["タグ1"].gsub("$$", spot.prefecture.name).sub("$", "")
tag2 = record["タグ2"].gsub("$$", spot.city.name).sub("$", "")
spot.tag_list = [tag1, tag2, record["タグ3"], record["タグ4"]].join(",")
spot.powered_by = record["管轄区域"]
else
raise "no model"
end
spot.save!
print "."
end
end
namespace :db do
desc "Stop情報をインポートする"
task "import_spots" => :environment do
Spot.destroy_all
import_spots(model: Cremation,
csv_obj: CSV.open("lib/tasks/csv/cremations.csv"))
import_spots(model: TaxOffice,
csv_obj: CSV.open("lib/tasks/csv/tax_offices.csv"),
except_column: ['斎場の特徴1', '斎場の特徴2'])
p
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment