ActAsCached
ActAsCached provides a lightweight second level cache.
Supports
- ActiveRecord associations
- ActtiveRecord::FinderMethods (primary key only)
Install
gem "act_as_cached", "~> 0.0.3"
Options:
- :prefix - Default is
aac
. - :cache_store - Customize cache store.
- :expires_time - Set cache expiration time, default is one week.
- :logger - Set output file with log, default is
Rails.logger
.
Usage
class Topic < ActiveRecord::Base
act_as_cached expires_time: 1.day
has_many :comments
belongs_to :user
end
class Comment < ActiveRecord::Base
act_as_cached expires_time: 2.days
belongs_to :topic
belongs_to :user
end
Topic.find(:first).comments.find(1).user
# Topic Load (0.4ms) SELECT `topics`.* FROM `topics` LIMIT 1
# Comment Load (0.4ms) SELECT `comments`.* FROM `comments` WHERE `comments`.`topic_id` = 1 AND `topics`.`id` = 1 LIMIT 1
# User Load (0.4ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
=> #<User id: 1 ,name: 'foo'>
Topic.find(:first)
=> #<Topic id: 1 ,title: 'foo'>
Comment.find(1)
=> #<Comment id: 1, content: "xxxx">
Comment.find(1).user
=> #<User id: 1, name: 'foo'>
Topic.find(:first).comments
# Comment Load (0.4ms) SELECT `comments`.* FROM `comments` WHERE `comments`.`topic_id` = 1 AND `topics`.`id` = 1 LIMIT 1
=> [#<Comment id: 1, content: 'xxxx'>,#<Comment id: 2, content: "ooooooo">]
Topic.find(:first).comments
=> [#<Comment id: 1, content: 'xxxx'>,#<Comment id: 2, content: "ooooooo">]
Topic.find(1)
# Topic Load (0.4ms) SELECT `topics`.* FROM `topics` WHERE `topics`.`id` = 1 LIMIT 1
=> #<Topic id: 1 ,title: 'foo'>
Topic.find(1).save # After you changes the object which was cached yet expired, the cache of the very object will be destroyed but not its associations.
Topic.find(1)
# Topic Load (0.5ms) SELECT `topics`.* FROM `topics` WHERE `topics`.`id` = 1 LIMIT 1
=> #<Topic id: 1 title: 'foo'>
Configure
Global Settings
ActAsCached.configure do
config.logger = ::Rails.logger
config.cache_store = ::Rails.cache
config.expires_time = 1.week
config.prefix = 'aac'
end
Tips
- Currently not support ActiveRecord::Relation#find , If you wrote the
default_scope
in your class, cache won't be enable.
TODO LIST
- Expires cache
- Add cache key rules
- Add test
Contributors
License
MIT License