Skip to content

Commit

Permalink
Merge pull request #496 from alphagov/round-petition-cache-key
Browse files Browse the repository at this point in the history
Round petition cache key
  • Loading branch information
h-lame authored Jun 28, 2016
2 parents 944f5c7 + c9b481c commit 2ac64b3
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
18 changes: 18 additions & 0 deletions app/models/petition.rb
Original file line number Diff line number Diff line change
Expand Up @@ -511,6 +511,24 @@ def set_petition_on_creator_signature
creator_signature.update_attribute(:petition_id, id)
end

def cache_key(*timestamp_names)
case
when new_record?
"petitions/new"
when timestamp_names.any?
timestamp = max_updated_column_timestamp(timestamp_names)
timestamp = timestamp.change(sec: (timestamp.sec.div(5) * 5))
timestamp = timestamp.utc.to_s(cache_timestamp_format)
"petitions/#{id}-#{timestamp}"
when timestamp = max_updated_column_timestamp
timestamp = timestamp.change(sec: (timestamp.sec.div(5) * 5))
timestamp = timestamp.utc.to_s(cache_timestamp_format)
"petitions/#{id}-#{timestamp}"
else
"petitions/#{id}"
end
end

def update_last_petition_created_at
Site.touch(:last_petition_created_at)
end
Expand Down
17 changes: 17 additions & 0 deletions spec/models/petition_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1764,5 +1764,22 @@
expect(petition.signatures_to_email_for('government_response')).to match_array [creator_signature, other_signature]
end
end

describe "#cache_key" do
let(:petition) { FactoryGirl.create(:petition, last_signed_at: "2016-06-28 00:00:17 UTC", open_at: "2016-06-28 00:00:07 UTC") }
let(:now) { "2016-06-29 00:00:07 UTC".in_time_zone }

around do |example|
travel_to(now) { example.run }
end

it "rounds down to the nearest 5 seconds" do
expect(petition.cache_key).to eq("petitions/#{petition.id}-20160629000005000000000")
end

it "can use other columns" do
expect(petition.cache_key(:open_at, :last_signed_at)).to eq("petitions/#{petition.id}-20160628000015000000000")
end
end
end
end

0 comments on commit 2ac64b3

Please sign in to comment.