Skip to content

Instantly share code, notes, and snippets.

@mewdriller
Created November 30, 2012 22:33
Show Gist options
  • Save mewdriller/4179185 to your computer and use it in GitHub Desktop.
Save mewdriller/4179185 to your computer and use it in GitHub Desktop.
class Genre < ActiveRecord::Base
attr_accessible :name
end
We can make this file beautiful and searchable if this error is corrected: No commas found in this CSV file in line 0.
name
TV Action & Adventure
TV Comedies
TV Dramas
Reality TV
Action & Adventure
Anime
Children & Family Movies
Classic Movies
Comedies
Documentaries
Dramas
Foreign Movies
Gay & Lesbian Movies
Horror Movies
Independent Movies
Romantic Movies
Sci-Fi & Fantasy
Sports Movies
Thrillers
require 'csv'
def seed_from_csv(relative_path, label, has_headers = true)
# Read in the CSV file:
CSV.read(Rails.root.join(relative_path), headers: has_headers).tap do |csv|
print "Seeding #{label}:\n"
# For each row in the CSV:
csv.each_with_index do |row, idx|
# Do whatever behavior is required to seed.
yield row if block_given?
ratio = (idx + 1).to_f / csv.size
per70 = (ratio * 70).round
filled = per70 < 2 ? 0 : (per70 - 1)
unfilled = 70 - per70
pad_percentage = ("%.2f" % (ratio * 100)).rjust(6)
progress = "%s%% [%s>%s]" % [ pad_percentage, ("=" * filled), (" " * unfilled) ]
# Update the progress bar display for the user.
print "\r#{progress}"
end
print "\n"
end
end
# Seed Genre data from associated CSV file.
seed_from_csv("db/seeds/genres.csv", "Genre") { |row| Genre.create!(name: row[0]) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment