CacheDriver
This gem makes rails model act as ActiveRecord, but not save data into database but cache system, file or redis
Installation
Add this line to your application's Gemfile:
gem 'cache_driver', '~> 0.3'
And then execute:
$ bundle
Or install it yourself as:
$ gem install cache_driver
Usage
Add following code to environments/development.rb or environments/production.rb
CacheDriver.setup do |config|
config.store = :file
config.file_dir = Rails.root.join('tmp', 'cache')
end
And then, create a model file in app/models
$ touch app/models/cache_model.rb
Just define model like below
class CacheModel < CacheRecord
def self.key_attr
"attr_name"
end
end
So you can use this model just like other ActiveRecord instance in controllers like
cache_models = CacheModel.find_all
cache_model = CacheModel.find_by_key key
cache_model = CacheModel.find_current
CacheModel.clear
cache_model.save
cache_model.destroy
By default, the attribute Fixnum
, String
, Array
, Hash
will be serialized to cache. But you should declare how to process other object such as Symbol or Class you creates
So you can customize the serialization method to change data which you want to cache by overriding the two methods below
def to_cache
hash = super
end
def self.from_cache(obj)
ins = super obj
end
Cache Inspect
Sometimes you need know the data detail in cache, So you can use a rake task supported by us.
$ bundle exec rake cache:inspect
Use the the command above to go to cache inspector and you will see the information below
CacheDriver >
After this you can use the following six commands to do something with the cache set by current project
CacheDriver > ? # show all commands and descriptions
CacheDriver > show models # list all models
CacheDriver > show keys <model> # list all keys of model in cache
CacheDriver > find <model> in <key> # fetch data of model with key
CacheDriver > save <model> to <key> withs <attr1>=<val1>,<attr2>=<val2>,... # update data of model, create one if not existed
CacheDriver > delete <model> in <key> # delete data of model
CacheDriver > clear <model> # delte all data of model
Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/goshan/cache_driver.
License
The gem is available as open source under the terms of the MIT License.