From 78c15d5810c65a612c02b562fd0aafcfb5db36ef Mon Sep 17 00:00:00 2001 From: Neil Lalonde Date: Mon, 9 Sep 2013 16:17:31 -0400 Subject: [PATCH] Move the unique post key storage code into the Post model --- app/models/post.rb | 10 ++++++++++ lib/post_creator.rb | 4 +--- lib/validators/post_validator.rb | 2 +- spec/components/validators/post_validator_spec.rb | 4 ++-- 4 files changed, 14 insertions(+), 6 deletions(-) diff --git a/app/models/post.rb b/app/models/post.rb index 0af2e472d..eca7cee99 100644 --- a/app/models/post.rb +++ b/app/models/post.rb @@ -70,6 +70,16 @@ class Post < ActiveRecord::Base "post-#{user_id}:#{raw_hash}" end + def store_unique_post_key + if SiteSetting.unique_posts_mins > 0 + $redis.setex(unique_post_key, SiteSetting.unique_posts_mins.minutes.to_i, "1") + end + end + + def matches_recent_post? + $redis.exists(unique_post_key) + end + def raw_hash return if raw.blank? Digest::SHA1.hexdigest(raw.gsub(/\s+/, "")) diff --git a/lib/post_creator.rb b/lib/post_creator.rb index 1a1427f68..a80f72d94 100644 --- a/lib/post_creator.rb +++ b/lib/post_creator.rb @@ -220,9 +220,7 @@ class PostCreator end def store_unique_post_key - if SiteSetting.unique_posts_mins > 0 - $redis.setex(@post.unique_post_key, SiteSetting.unique_posts_mins.minutes.to_i, "1") - end + @post.store_unique_post_key end def consider_clearing_flags diff --git a/lib/validators/post_validator.rb b/lib/validators/post_validator.rb index 1386f11c9..124d55058 100644 --- a/lib/validators/post_validator.rb +++ b/lib/validators/post_validator.rb @@ -64,7 +64,7 @@ class Validators::PostValidator < ActiveModel::Validator # If the post is empty, default to the validates_presence_of return if post.raw.blank? - if $redis.exists(post.unique_post_key) + if post.matches_recent_post? post.errors.add(:raw, I18n.t(:just_posted_that)) end end diff --git a/spec/components/validators/post_validator_spec.rb b/spec/components/validators/post_validator_spec.rb index 00e39f21c..76865503d 100644 --- a/spec/components/validators/post_validator_spec.rb +++ b/spec/components/validators/post_validator_spec.rb @@ -38,7 +38,7 @@ describe Validators::PostValidator do context "post is unique" do before do - $redis.stubs(:exists).with(post.unique_post_key).returns(nil) + post.stubs(:matches_recent_post?).returns(false) end it "should not add an error" do @@ -49,7 +49,7 @@ describe Validators::PostValidator do context "post is not unique" do before do - $redis.stubs(:exists).with(post.unique_post_key).returns('1') + post.stubs(:matches_recent_post?).returns(true) end it "should add an error" do