From ec26063fdce97ac6b6c7b0c2562bd890d15abcb3 Mon Sep 17 00:00:00 2001 From: Neil Lalonde Date: Fri, 6 Dec 2013 14:38:55 -0500 Subject: [PATCH] In populate:posts tool, catch post validation errors and retry --- lib/tasks/populate.thor | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/lib/tasks/populate.thor b/lib/tasks/populate.thor index 6ab703c6ae5..0b653287d37 100644 --- a/lib/tasks/populate.thor +++ b/lib/tasks/populate.thor @@ -1,5 +1,7 @@ class Populate < Thor + MAX_ERRORS = 5 + desc "posts", "Generate posts in a topic" long_desc <<-LONGDESC Create a topic with any number of posts, or add posts to an existing topic. @@ -54,17 +56,37 @@ class Populate < Thor puts "Making #{options[:num_posts]} posts" + num_errors = 0 + (start_post..options[:num_posts]).each do |num| print '.' raw = rand(4) == 0 ? (rand(2) == 0 ? image_posts.sample : wikipedia_posts.sample ) : hipster_words.sample(20).join(' ') post_creator = PostCreator.new(users[num % (users.length)], topic_id: topic.id, raw: raw) post_creator.create + if post_creator.errors.present? + # It's probably a "Body is too similar to what you recently posted" error. + # Try one more time using more random words. + post_creator = PostCreator.new(users[num % (users.length)], topic_id: topic.id, raw: hipster_words.sample(40).join(' ')) + post_creator.create + if post_creator.errors.present? + # Still failing! Show the error. + puts '', "--------------------------" + puts "ERROR creating a post!" + puts post_creator.errors.full_messages + puts "--------------------------" + + # Stop looping after MAX_ERRORS errors + num_errors += 1 + if num_errors > MAX_ERRORS + puts "Giving up. Too many errors." + exit 1 + end + end + end end puts '' - RateLimiter.enable - puts "Done. Topic id = #{topic.id}" ensure RateLimiter.enable