Skip to content

Instantly share code, notes, and snippets.

@shirashin
Created January 24, 2013 17:21
Show Gist options
  • Select an option

  • Save shirashin/4625358 to your computer and use it in GitHub Desktop.

Select an option

Save shirashin/4625358 to your computer and use it in GitHub Desktop.
RailsのシードファイルをCSVで運用してみるテスト
# CSV seedfile
# load csv seedfile on rails.
#
# db/
# ├── seeds
# │ └── User-0000.csv <-- seed csv
# └── seeds.rb <-- It's me
#
# [csv]
# name,email,password,role
# taro yamada,[email protected],hogehoge,admin
#
require 'csv'
class CSV2Table
def self.parse(path)
ary = []
File.open(path, 'r') do |f|
header_str = f.gets
header = CSV.parse_line(header_str)
while columns_str = f.gets
hash = {}
columns = CSV.parse_line(columns_str)
if columns.size == header.size
header.size.times do |i|
hash[header[i].to_sym] = columns[i]
end
ary << hash
end
end
end
return ary
end
end
Dir.glob(File.join(Rails.root, 'db', 'seeds', '*.csv')).sort.each do |file|
desc "Load the seed data from db/seeds/#{File.basename(file)}."
table_name, = File.basename(file).split(/[-.]/)
table_data = CSV2Table.parse(file)
eval(table_name).delete_all
table_data.each do |hash|
eval(table_name).create!(hash)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment