Skip to content

Instantly share code, notes, and snippets.

@ilyabrin
Last active October 10, 2015 14:27
Show Gist options
  • Select an option

  • Save ilyabrin/3704481 to your computer and use it in GitHub Desktop.

Select an option

Save ilyabrin/3704481 to your computer and use it in GitHub Desktop.
DBF to SQL
#!/usr/bin/ruby
# load the required library
require 'rubygems'
require 'dbf'
require 'yaml'
require 'active_record'
# check the command line argument
def check_argument
if ARGV.count.zero? # ARGV hold all the arguments given on the command line
puts "Usage: dbf2mysql dirname" # puts always returns nil
else
dir = ARGV.first # get the first argument
unless File.directory? dir # is it a directory?
puts "#{dir} is not a folder"
else
Dir.new dir
end
end
end
def check_conf(dir,conf_file)
if dir.entries.include? conf_file # the configuration must reside in the directory
YAML::load_file(File.join(dir.path,conf_file)) # load the yaml file
else
puts 'configuration not found'
end
end
dir = check_argument
db = check_conf(dir,'database.yml') unless dir.nil?
if db
ActiveRecord::Base.establish_connection(db['default']) # connect to database
dir.entries.each do |file|
fname = File.join(dir.path, file)
table_name = file[0...(file.index '.' )]
if file =~ /\.DBF$/
table = DBF::Table.new(fname) # create table from the dbf file
eval(table.schema.gsub(table_name, table_name.downcase)) # create the table in mysql
# generate the model class on the fly with ActiveRecord::Base as its superclass
model = Class.new ActiveRecord::Base do
self.table_name = table_name.downcase
Object.const_set table_name.capitalize, self
end
# insert each column into the table in mysql
table.records.each do |rec|
model.create(rec.attributes)
end
puts "#{table.records.count} record(s) inserted"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment