Count view only once in the same browser
parent
7a3bc80340
commit
013eade63c
@ -0,0 +1,22 @@
|
|||||||
|
class ViewCounter
|
||||||
|
attr_reader :asciicast, :storage
|
||||||
|
|
||||||
|
def initialize(asciicast, storage)
|
||||||
|
@asciicast = asciicast
|
||||||
|
@storage = storage
|
||||||
|
end
|
||||||
|
|
||||||
|
def increment
|
||||||
|
unless storage[key]
|
||||||
|
Asciicast.increment_counter(:views_count, asciicast.id)
|
||||||
|
asciicast.reload
|
||||||
|
storage[key] = '1'
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def key
|
||||||
|
@key ||= :"asciicast_#{asciicast.id}_viewed"
|
||||||
|
end
|
||||||
|
end
|
@ -0,0 +1,27 @@
|
|||||||
|
require 'spec_helper'
|
||||||
|
|
||||||
|
describe ViewCounter do
|
||||||
|
let(:view_counter) { ViewCounter.new(asciicast, storage) }
|
||||||
|
let(:asciicast) { create(:asciicast) }
|
||||||
|
let(:storage) { {} }
|
||||||
|
|
||||||
|
describe '#increment' do
|
||||||
|
context "when called for the first time" do
|
||||||
|
it "increments the views_count" do
|
||||||
|
expect { view_counter.increment }.
|
||||||
|
to change(asciicast, :views_count).by(1)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
context "when called for the second time" do
|
||||||
|
before do
|
||||||
|
view_counter.increment
|
||||||
|
end
|
||||||
|
|
||||||
|
it "doesn't increment the views_count" do
|
||||||
|
expect { view_counter.increment }.
|
||||||
|
not_to change(asciicast, :views_count)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
Loading…
Reference in New Issue