Simple Cache is a library which caches the model objects and their associations. It's simple! Nothing needs to be done to cache and refresh the model objects!
Let's say there are the following two models with a one-to-many relationship.
class User < ApplicationRecord
has_one_cached :player
endclass Player < ApplicationRecord
endAt first, the player object, which are the user object's associations, will be retrieved from the database when executing the following sample snippet. At the same time, the player object ids will be stored in the Memcached automatically.
When executing the following code again, player object ids will be retrieved from the Memcached, not the database.
User.take.cached_player
Simple Cache removes the objects from the Memcached when committing a transaction in your program, to keep them up-to-date. Then they are retrieved from the database and stored onto the Memcached again.
Add this line to Gemfile:
gem 'ar-simple-cache', github: 'begaborn/simple_cache'
Currently, SimpleCache supports Rails 4.2 or later.
bundle install
class User < ApplicationRecord
use_find_cache # Delare that you'll use method 'find_cache'
end
User.find_cache(1)class User < ActiveRecord::Base
has_one_cached :account
end
User.take.cached_accountclass User < ActiveRecord::Base
has_many_cached_ids_of :players
end
User.cached_player_ids
# => [1, 2, 3] # Array [Player's ids]class Player < ActiveRecord::Base
belongs_to_cached :user
end- If any option below is specified for
has_many,has_one,belongs_tothe model objects will not be cached.
:as, :through, :primary_key, :source, :source_type, :inverse_of, :polymorphic
Bug reports and pull requests are welcome on GitHub at https://github.com/begaborn/simple_cache. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.
The gem is available as open source under the terms of the MIT License.
