Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add expirable Rails.cache capability #112

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 22 additions & 8 deletions app/models/shortener/shortened_url.rb
Original file line number Diff line number Diff line change
Expand Up @@ -84,16 +84,17 @@ def self.extract_token(token_str)
end

def self.fetch_with_token(token: nil, additional_params: {}, track: true)
shortened_url = ::Shortener::ShortenedUrl.unexpired.where(unique_key: token).first

url = if shortened_url
shortened_url.increment_usage_count if track
merge_params_to_url(url: shortened_url.url, params: additional_params)
if ::Shortener.cache_urls
cache_key = "shortener:#{token}"
cache_key << ":#{Digest::MD5.hexdigest(additional_params.to_s)}" if additional_params.present?
result = Rails.cache.fetch(cache_key, expires_in: ::Shortener.cache_expiration) do
lookup_by_token(token, additional_params, false)
end
result[:shortened_url].increment_usage_count if track && result[:shortened_url]
result
else
Shortener.default_redirect || '/'
lookup_by_token(token, additional_params, track)
end

{ url: url, shortened_url: shortened_url }
end

def self.merge_params_to_url(url: nil, params: {})
Expand Down Expand Up @@ -125,6 +126,19 @@ def to_param

private

def self.lookup_by_token(token, additional_params, track)
shortened_url = ::Shortener::ShortenedUrl.unexpired.where(unique_key: token).first

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

::Shortener::ShortenedUrl.unexpired.where(unique_key: token).first should be ::Shortener::ShortenedUrl.unexpired.find_by(unique_key: token)

Copy link
Author

@pinnymz pinnymz Sep 16, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@lifeiscontent, pretty sure find_by is not supported by Rails 3. I'm fine with that personally, but the README states that Rails 3 is a target for this project (see https://github.com/jpmcgrath/shortener#dependencies and https://github.com/jpmcgrath/shortener#installation)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah, ok, makes sense 👍


url = if shortened_url
shortened_url.increment_usage_count if track
merge_params_to_url(url: shortened_url.url, params: additional_params)
else
Shortener.default_redirect || '/'
end

{ url: url, shortened_url: shortened_url }
end

def self.unique_key_candidate
charset = ::Shortener.key_chars
(0...::Shortener.unique_key_length).map{ charset[rand(charset.size)] }.join
Expand Down
8 changes: 8 additions & 0 deletions lib/shortener.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,14 @@ module Shortener
mattr_accessor :persist_retries
self.persist_retries = 3

# cache_urls - set to true to cache fetched urls using Rails.cache
mattr_accessor :cache_urls
self.cache_urls = false

# cache_expiration - duration after which the cache should expire
mattr_accessor :cache_expiration
self.cache_expiration = nil

def self.key_chars
CHARSETS[charset]
end
Expand Down
89 changes: 88 additions & 1 deletion spec/models/shortened_url_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@
require 'spec_helper'

describe Shortener::ShortenedUrl, type: :model do
it { is_expected.to belong_to :owner }
if ActiveRecord::VERSION::MAJOR >= 5
it { is_expected.to belong_to(:owner).optional }
else
it { is_expected.to belong_to :owner }
end

it { is_expected.to validate_presence_of :url }

describe '#generate!' do
Expand Down Expand Up @@ -278,10 +283,31 @@
end
end

shared_context 'caching enabled' do
around do |example|
current = Shortener.cache_urls
Shortener.cache_urls = true
example.run
Shortener.cache_urls = current
end
let(:memory_store) { ActiveSupport::Cache.lookup_store(:memory_store) }
let(:cache) { Rails.cache }
before do
allow(Rails).to receive(:cache).and_return(memory_store)
Rails.cache.clear
end
end

context 'invalid token' do
it_should_behave_like 'invalid token supplied' do
let(:token) { 'invalid_token'}
end

include_context 'caching enabled' do
it_should_behave_like 'invalid token supplied' do
let(:token) { 'invalid_token'}
end
end
end

context 'valid token' do
Expand All @@ -304,6 +330,67 @@
Shortener::ShortenedUrl.fetch_with_token(token: short_url.unique_key, track: false)
end
end

include_context 'caching enabled' do
context 'on first request' do
it 'caches the model' do
expect(cache.exist?("shortener:#{short_url.unique_key}")).to eq false
result = Shortener::ShortenedUrl.fetch_with_token(token: short_url.unique_key)
expect(cache.read("shortener:#{short_url.unique_key}")).to eq result
end
it "increments use count" do
expect_any_instance_of(Shortener::ShortenedUrl).to receive(:increment_usage_count)
Shortener::ShortenedUrl.fetch_with_token(token: short_url.unique_key)
end

context 'with cache_expiration configured' do
around do |example|
current = Shortener.cache_expiration
Shortener.cache_expiration = 5.minutes
example.run
Shortener.cache_expiration = current
end
it 'caches the model for the specified duration' do
Shortener::ShortenedUrl.fetch_with_token(token: short_url.unique_key)
entry = cache.send(:read_entry, "shortener:#{short_url.unique_key}", {})
expected_expiration = Time.now.to_f + Shortener.cache_expiration
expect(entry.expires_at).to be_within(5).of(expected_expiration)
end
end

context 'with additional_params' do
it 'caches using a digest of the given params' do
params = {foo: :bar}
result = Shortener::ShortenedUrl.fetch_with_token(token: short_url.unique_key, additional_params: params)
cache_key = "shortener:#{short_url.unique_key}:#{Digest::MD5.hexdigest(params.to_s)}"
expect(cache.read(cache_key)).to eq result
end
end
end

context 'on subsequent requests' do
let(:cached) { {url: url, shortened_url: short_url} }
before do
cache.write("shortener:#{short_url.unique_key}", cached)
expect_any_instance_of(ActiveRecord::Relation).to receive(:first).never
end

it 'retrieves from cache' do
result = Shortener::ShortenedUrl.fetch_with_token(token: short_url.unique_key)
expect(result).to eq cached
end
it 'increments use count' do
expect_any_instance_of(Shortener::ShortenedUrl).to receive(:increment_usage_count)
Shortener::ShortenedUrl.fetch_with_token(token: short_url.unique_key)
end
context 'with track set to false' do
it 'does not increment use count' do
expect_any_instance_of(Shortener::ShortenedUrl).not_to receive(:increment_usage_count)
Shortener::ShortenedUrl.fetch_with_token(token: short_url.unique_key, track: false)
end
end
end
end
end

context 'expired short url' do
Expand Down