Skip to content

Instantly share code, notes, and snippets.

@Epictetus
Forked from wtnabe/README.md
Created April 18, 2011 21:53
Show Gist options
  • Save Epictetus/926276 to your computer and use it in GitHub Desktop.
Save Epictetus/926276 to your computer and use it in GitHub Desktop.
# -*- mode: ruby; coding: utf-8 -*-
class SeedImporter
def initialize
@model = nil
@with_id = false
end
def run
Dir.glob( File.dirname(__FILE__) + '/seeds/**/*.{yml,csv}' ).sort.each { |seed|
send( "import_#{File.extname( seed )[1..seed.bytesize]}_seed", seed )
}
end
def fcsv_opts
{ :headers => true,
:header_converters => :downcase }
end
def import_csv_seed( file )
init_model( file, '.csv' )
FasterCSV.table( file, fcsv_opts ) { |csv|
@with_id = csv.headers.include?( 'id' )
}
if ( @with_id )
_import_csv( file ) { |row| create_and_save_with_id( row.to_hash ) }
else
_import_csv( file ) { |row| create_and_save( row.to_hash ) }
end
end
def _import_csv( file, &block )
FasterCSV.open( file, fcsv_opts ).each { |csv| block.call( csv ) }
end
def import_yml_seed( file )
init_model( file, '.yml' )
YAML.load_file( file ).each { |r|
if ( r.has_key?( 'id' ) )
create_and_save_with_id( r )
else
create_and_save( r )
end
}
end
def to_model( file, suffix )
File.basename( file, suffix ).sub( /\A[0-9]+(_\.)?/, '' ).classify
end
def init_model( file, suffix )
@model = Object.const_get( to_model( file, suffix ) )
end
def create_and_save( data )
@model.create!( data )
end
def create_and_save_with_id( data )
record = @model.new( data )
record['id'] = data['id']
record.save!
end
end
SeedImporter.new.run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment