From e67a03bbe37f15055e1ea22500565c262697109d Mon Sep 17 00:00:00 2001 From: Philipp Fischbeck Date: Sun, 1 Mar 2015 20:56:30 +0100 Subject: [PATCH] Add function for updating problem count --- app/models/problem.rb | 9 +++++++++ test/models/problem_test.rb | 17 +++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/app/models/problem.rb b/app/models/problem.rb index 7747ddd..5bec039 100644 --- a/app/models/problem.rb +++ b/app/models/problem.rb @@ -15,4 +15,13 @@ class Problem < ActiveRecord::Base def original_url "https://projecteuler.net/problem=#{self.id}" end + + def self.update_count(new_count) + old_count = Problem.count + raise ArgumentError, "new count has to be larger than old count" if new_count < old_count + + new_count.times do |i| + Problem.where(id: i + 1).first_or_create! + end + end end diff --git a/test/models/problem_test.rb b/test/models/problem_test.rb index 595651f..67551ca 100644 --- a/test/models/problem_test.rb +++ b/test/models/problem_test.rb @@ -17,4 +17,21 @@ class ProblemTest < ActiveSupport::TestCase test "should have correct original url" do assert_equal "https://projecteuler.net/problem=1", problems(:one).original_url end + + test "should allow for problem count updating" do + Problem.update_count(10) + assert_not Problem.where(id: 0).exists? + (1..10).each do |i| + assert Problem.where(id: i).exists? + end + assert_equal "First title", Problem.find(1).title + end + + test "should not allow decreasing problem count update" do + + assert_raises ArgumentError do + Problem.update_count(1) + end + assert_equal 3, Problem.count() + end end