Created
June 3, 2012 12:40
-
-
Save Sija/2863325 to your computer and use it in GitHub Desktop.
YAML data seeds importer for Rails 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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