Last active
April 8, 2025 07:10
-
-
Save rpbaptist/985646184fcdf1083acd1ccbb15061f7 to your computer and use it in GitHub Desktop.
A cache wrapper implementation with simple interface
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# spec/support/shared/examples/cachable.rb | |
# frozen_string_literal: true | |
# Provide a simple interface for caching methods | |
# Usage example: | |
# | |
# class Foo | |
# include Cachable | |
# cache :bar | |
# | |
# def bar | |
# # some database query method | |
# end | |
# end | |
module Cachable | |
extend ActiveSupport::Concern | |
CACHE_OPTIONS = { | |
expires_in: 1.day | |
}.freeze | |
class_methods do | |
def cache(*method_names, options: CACHE_OPTIONS) | |
cacher.module_eval do | |
Array(method_names).each do |method_name| | |
define_method(method_name) do |*args| | |
cached(method_name, args, options) { super(*args) } | |
end | |
end | |
end | |
prepend cacher | |
end | |
def cacher | |
@cacher ||= Module.new | |
end | |
end | |
private | |
def cached(method_name, args, options = CACHE_OPTIONS) | |
Rails.cache.fetch([self.class, method_name, args], options) do | |
yield | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment