Skip to content

Instantly share code, notes, and snippets.

@fadhlirahim
Last active September 16, 2016 02:08
Show Gist options
  • Save fadhlirahim/8107c00a4ff0c1590c01b4bbb0ba173e to your computer and use it in GitHub Desktop.
Save fadhlirahim/8107c00a4ff0c1590c01b4bbb0ba173e to your computer and use it in GitHub Desktop.
A module to create cache key using ruby. Often I find myself putting arbitrary strings all over the place in my code base. This module helps as being the 1 place in the code base to define what each key represents
module Cache
# Placeholder for your redis key prefixes
# Serves as a way to identify which prefix keys belongs to which cache key resource
#
# Usage:
#
# To create cache key
#
# Cache::Key.prefix(Cache::Key::PRESENTER, resource)
# => "pr:Track:#{track.id}:"
#
# Cache::Key.prefix(Cache::Key::PRESENTER, resource, {country: "my"})
# => "pr:Track:#{track.id}:country:my"
#
class Key
PRESENTER = "pr:".freeze
VIDEO_URL = "v:url".freeze
APPS = "a".freeze
def self.prefix(prefix, resource, *args)
"#{prefix}#{resource.class.name}:#{resource.id}:#{permutations(args)}"
end
def self.simple_prefix(prefix, id)
"#{prefix}#{id}"
end
def self.permutations(args)
return if args.blank?
args.map do |a|
case a
when Array
a.join(":")
when Hash
a.map{|e| e}.join(":")
else
a
end
end.join(":")
end
end
end
# using rspec
describe Cache::Key do
describe ".prefix" do
let(:track) { create(:track) }
let(:video) { create(:video) }
it "returns a string prefix to use for presenters redis key" do
str = described_class.prefix(Cache::Key::PRESENTER, track)
expect(str).to eq "pr:Track:#{track.id}:"
end
it "returns a string prefix to use for video url redis key" do
str = described_class.prefix(Cache::Key::VIDEO_URL, video)
expect(str).to eq "v:url:Video:#{video.id}:"
end
describe "accepts extra arguments to create uniq key" do
context "when array" do
it "append map joins elements to string" do
str = described_class.prefix(Cache::Key::VIDEO_URL, video, [1, 2])
expect(str).to eq "v:url:Video:#{video.id}:1:2"
end
end
context "when hash" do
it "append map joins elements to string" do
str = described_class.prefix(Cache::Key::VIDEO_URL, video, {foo: 'bar', baz: 'foo'})
expect(str).to eq "v:url:Video:#{video.id}:foo:bar:baz:foo"
end
end
it "append element to string" do
str = described_class.prefix(Cache::Key::VIDEO_URL, video, "foo")
expect(str).to eq "v:url:Video:#{video.id}:foo"
end
end
end
describe ".simple_prefix" do
it do
expect(Cache::Key.simple_prefix(Cache::Key::APPS, 1)).to eq "a:1"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment