Skip to content
Browse files

Refactoring the generation of sample data

  • Loading branch information...
1 parent ec97227 commit b4e36644f4c07b9d87a60f80364009578db0763b @jcasimir jcasimir committed
Showing with 27 additions and 11 deletions.
  1. +14 −0 app/models/article.rb
  2. +4 −0 app/models/tag.rb
  3. +2 −11 db/seeds.rb
  4. +7 −0 lib/tasks/sample_data.rake
View
14 app/models/article.rb
@@ -52,4 +52,18 @@ def word_count
def self.total_word_count
all.inject(0) {|total, a| total += a.word_count }
end
+
+ def self.generate_samples(quantity = 1000)
+ tags = Tag.all
+ quantity.times do
+ article = Fabricate(:article)
+ article.created_at = article.created_at - (rand(300) + 100).hours
+ article.tags = tags.sort_by{ rand }[0..rand(tags.length)]
+ article.save
+ (rand(10)).times do
+ Fabricate(:comment, :article => article, :created_at => article.created_at + rand(100).hours)
+ end
+ yield if block_given?
+ end
+ end
end
View
4 app/models/tag.rb
@@ -5,4 +5,8 @@ class Tag < ActiveRecord::Base
def to_s
name
end
+
+ def self.generate_samples(quantity = 10)
+ quantity.times{ Fabricate(:tag) }
+ end
end
View
13 db/seeds.rb
@@ -6,14 +6,5 @@
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
-tags = (0..10).collect{ Fabricate(:tag) }
-
-10.times do
- article = Fabricate(:article)
- article.created_at = article.created_at - (rand(300) + 100).hours
- article.tags = tags.sort_by{ rand }[0..rand(tags.length)]
- article.save
- (rand(10)).times do
- Fabricate(:comment, :article => article, :created_at => article.created_at + rand(100).hours)
- end
-end
+Tag.generate_samples(10)
+Article.generate_samples(10)
View
7 lib/tasks/sample_data.rake
@@ -0,0 +1,7 @@
+namespace :samples do
+ task :generate_many => :environment do
+ puts "Generating 1000 sample articles..."
+ Article.generate_samples(1000){ printf "." }
+ puts ""
+ end
+end

0 comments on commit b4e3664

Please sign in to comment.
Something went wrong with that request. Please try again.