Skip to content

Instantly share code, notes, and snippets.

@Sija
Created June 3, 2012 12:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sija/2863325 to your computer and use it in GitHub Desktop.
Save Sija/2863325 to your computer and use it in GitHub Desktop.
YAML data seeds importer for Rails 3
require 'active_record/fixtures'
namespace :db do
desc 'Seed the database with once/ and always/ fixtures.'
task :seed => :environment do
load_fixtures 'seed/once'
load_fixtures 'seed/always', :always
end
desc 'Seed the database with develop/ fixtures.'
task :develop => :environment do
load_fixtures 'seed/develop', :always
end
private
def load_fixtures(dir, always = false)
Dir.glob(File.join(Rails.root, 'db', dir, '*.yml')).each do |fixture_file|
table_name = File.basename(fixture_file, '.yml')
if always || table_empty?(table_name)
ActiveRecord::Fixtures.create_fixtures(File.join('db', dir), table_name)
end
end
end
def table_empty?(table_name)
quoted = connection.quote_table_name(table_name)
connection.select_value("SELECT COUNT(*) FROM #{quoted}").to_i.zero?
end
def connection
ActiveRecord::Base.connection
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment