Created
August 30, 2018 14:21
-
-
Save krisleech/e71341757c79930c810e8c8053ecb233 to your computer and use it in GitHub Desktop.
Listener to bust cache key for event
This file contains 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
# Cache buster | |
# Generic object which will invalidate a cache key for an event. | |
class CacheBuster | |
def initialize(dependencies = {}) | |
@cache = dependencies.fetch(:cache) { Rails.cache } | |
end | |
def self.build(options) | |
new.tap do |instance| | |
instance.cache_key = options.fetch(:cache_key) | |
instance.event_name = options.fetch(:event_name) | |
end | |
end | |
def method_missing(name, _) | |
if event_name == name.to_s | |
@cache.delete(cache_key) | |
else | |
super | |
end | |
end | |
def respond_to?(name) | |
event_name == name.to_s || super | |
end | |
end | |
# usage | |
command.subscribe(CacheBuster.build(cache_key: :quick_search, event: :on_field_updated)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment