Skip to content

Instantly share code, notes, and snippets.

@chaffeqa
Last active April 3, 2023 16:19
Show Gist options
  • Save chaffeqa/6c74348df87df337141f4648089b8319 to your computer and use it in GitHub Desktop.
Save chaffeqa/6c74348df87df337141f4648089b8319 to your computer and use it in GitHub Desktop.
ActiveSupport::Concern and Sorbet RBI solution
# typed: true
module AllCachedModelConcern
extend ActiveSupport::Concern
included do
after_save(:clear_all_cached!)
after_destroy(:clear_all_cached!)
end
def clear_all_cached!
self.class.all_cached_backend.delete(self.class.all_cached_key) if self.class.all_cached_backend
end
class_methods do
def all_cached_key
"#{self}:all_cached"
end
def cached_find(id)
cached_find_all([id]).first
end
def cached_find!(id)
cached_find(id) || raise(ActiveRecord::RecordNotFound, "Couldn't find #{self} with ID=#{id}")
end
def cached_find_all(ids)
all_cached.select { |record| ids.map(&:to_i).include?(record.id) }
end
def all_cached
if all_cached_backend.nil?
order("id ASC").to_a
else
all_cached_backend.fetch(all_cached_key, expires_in: 5.minutes) { order("id ASC").to_a }
end
end
def all_cached_backend
Rails.cache
end
end
end
# typed: true
module AllCachedModelConcern
extend ::ActiveSupport::Concern
extend T::Sig
extend T::Helpers
requires_ancestor { T.class_of(ActiveRecord::Base) }
requires_ancestor { Kernel }
sig { void }
def clear_all_cached!; end
module ClassMethods
extend T::Sig
extend T::Helpers
requires_ancestor { T.class_of(ActiveRecord::Base) }
requires_ancestor { Kernel }
TIdParam = T.type_alias { T.any(String, Integer) }
TSelf = T.type_alias { T.self_type }
sig { returns(String) }
def all_cached_key; end
sig { params(id: TIdParam).returns(T.nilable(TSelf)) }
def cached_find(id); end
sig { params(id: TIdParam).returns(TSelf) }
def cached_find!(id); end
sig { returns(T::Array[TSelf]) }
def all_cached; end
sig { params(ids: T::Array[TIdParam]).returns(T::Array[TSelf]) }
def cached_find_all(ids); end
sig { returns(ActiveSupport::Cache::Store) }
def all_cached_backend; end
end
mixes_in_class_methods(ClassMethods)
end