{"id":15288785,"url":"https://github.com/khiav223577/active_model_cachers","last_synced_at":"2025-08-31T15:13:35.685Z","repository":{"id":53171161,"uuid":"131403208","full_name":"khiav223577/active_model_cachers","owner":"khiav223577","description":"Simply cache whatever you want by using cachers which will help you maintain cached objects and expire them when they are changed.","archived":false,"fork":false,"pushed_at":"2024-09-14T18:06:34.000Z","size":370,"stargazers_count":63,"open_issues_count":2,"forks_count":9,"subscribers_count":5,"default_branch":"master","last_synced_at":"2025-08-25T04:45:05.219Z","etag":null,"topics":["activerecord","cachemanager","rails","rubygems"],"latest_commit_sha":null,"homepage":"","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/khiav223577.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-04-28T11:18:51.000Z","updated_at":"2024-09-14T18:06:38.000Z","dependencies_parsed_at":"2024-10-30T02:28:24.519Z","dependency_job_id":null,"html_url":"https://github.com/khiav223577/active_model_cachers","commit_stats":{"total_commits":405,"total_committers":6,"mean_commits":67.5,"dds":"0.051851851851851816","last_synced_commit":"2d023333242cc8dad8d51e06f64774f4fcd3ad6c"},"previous_names":[],"tags_count":14,"template":false,"template_full_name":null,"purl":"pkg:github/khiav223577/active_model_cachers","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/khiav223577%2Factive_model_cachers","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/khiav223577%2Factive_model_cachers/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/khiav223577%2Factive_model_cachers/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/khiav223577%2Factive_model_cachers/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/khiav223577","download_url":"https://codeload.github.com/khiav223577/active_model_cachers/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/khiav223577%2Factive_model_cachers/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":272996164,"owners_count":25028070,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-08-31T02:00:09.071Z","response_time":79,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["activerecord","cachemanager","rails","rubygems"],"created_at":"2024-09-30T15:53:10.287Z","updated_at":"2025-08-31T15:13:35.639Z","avatar_url":"https://github.com/khiav223577.png","language":"Ruby","funding_links":[],"categories":[],"sub_categories":[],"readme":"# ActiveModelCachers\n\n[![Gem Version](https://img.shields.io/gem/v/active_model_cachers.svg?style=flat)](http://rubygems.org/gems/active_model_cachers)\n[![Build Status](https://github.com/khiav223577/active_model_cachers/workflows/Ruby/badge.svg)](https://github.com/khiav223577/active_model_cachers/actions)\n[![RubyGems](http://img.shields.io/gem/dt/active_model_cachers.svg?style=flat)](http://rubygems.org/gems/active_model_cachers)\n[![Code Climate](https://codeclimate.com/github/khiav223577/active_model_cachers/badges/gpa.svg)](https://codeclimate.com/github/khiav223577/active_model_cachers)\n[![Test Coverage](https://codeclimate.com/github/khiav223577/active_model_cachers/badges/coverage.svg)](https://codeclimate.com/github/khiav223577/active_model_cachers/coverage)\n\nActiveModelCachers provides cachers to models and allows the users to specify what needs to be cached. The data will be cached at `Rails.cache` and also at application level via `RequestStore`, to cache values between requests. The cachers will maintain cached objects and expire them when they are changed (e.g. created, updated, destroyed, or deleted).\n\nActiveModelCachers:\n\n- Uses multiple levels of cache ([Multi-level Cache](#multi-level-cache))\n- Does not pollute the original ActiveModel API\n- Has high test coverage\n\n## Supports\n\n- Ruby 2.3 ~ 2.7\n- Rails 3.2, 4.2, 5.0, 5.1, 5.2, 6.0\n\n## Table of contents\n\n1. [Compare with identity_cache](#compare-with-identity_cache)\n2. [Installation](#installation)\n3. [Usage](#usage)\n4. [Examples](#examples)\n5. [Smart Caching](#smart-caching)\n6. [Convenient syntax sugar for caching ActiveRecord](#convenient-syntax-sugar-for-caching-activerecord)\n7. [Options](#options)\n8. [Future Works](#future-works)\n9. [Development](#development)\n10. [Contributing](#contributing)\n11. [License](#license)\n\n## Compare with [identity_cache](https://github.com/Shopify/identity_cache)\n\n`active_model_cachers` allows you to specify what to cache and when to expire those caches, so that you can cache raw sql query results, time-consuming methods, responses of requests, and so on. It also supports AR associations/attributes (has_many, has_one, belongs_to) and secondary indexes.\n\n`identity_cache` focuses on AR, and doesn't have the flexibility to specify the query.`identity_cache` has more features for caching AR associations/attributes. Some of these feature are: Caching attributes by multiple keys, embedding associations to load data in one fetch, non-unique secondary indexes, and caching polymorphic associations.\n\nAnother important difference is that `active_model_cachers` encapsulates methods to `cacher`, while `identity_cache` adds a number of `fetch_*` method to `AR` directly, therefore it's more possible to have method name collision when using `identity_cache`.\n\n## Installation\n\nTo install active_model_cachers, add this line to your application's Gemfile:\n\n```ruby\ngem 'active_model_cachers'\n```\n\nThen execute:\n\n    $ bundle\n\nOr install it yourself by executing:\n\n    $ gem install active_model_cachers\n\nAdd an initializer with this code to your project:\n\n```rb\nActiveModelCachers.config do |config|\n  config.store = Rails.cache # specify where the cache will be stored\nend\n```\n\n## Usage\n\n### The `cache_at` method\n\nUse the `cache_at` method to cache whatever you want. Specify a cache on the model:\n\n`cache_at(name, query = nil, options = {})`\n\nParameters:\n - name: the attribute name\n - query: how to get data on cache miss. It will be set automatically if the name matches an association or an attribute.\n - options: see [here](#options)\n\n### Access the cached attributes\n\nTo avoid method name collision, all methods will be defined on the `Cacher` instead of `ActiveModel`. You can get the `cacher` from the class or from the instance (e.g. `User.cacher` or `user.cacher`), then access cached attributes via the method defined by `cache_at` (e.g. `user.cacher.the_attribute_name`).\n\n### Basic Example\n```rb\nclass User \u003c ActiveRecord::Base\n  cache_at :something_you_want_to_cache, -\u003e{ get_the_data_on_cache_miss }\nend\n\nuser.cacher.something_you_want_to_cache\n```\n\n\n## Examples\n\n### Example 1: Cache the number of active users\nSpecify the method name as `active_count`. After using lambda `User.active.count` to define how the data can be accessed when there is a cache miss, you can get the cached data by calling `active_count` method on the cacher `User.cacher`.\n\n```rb\nclass User \u003c ActiveRecord::Base\n  scope :active, -\u003e{ where('last_login_at \u003e ?', 7.days.ago) }\n  cache_at :active_count, -\u003e{ active.count }, expire_by: 'User#last_login_at'\nend\n\n@count = User.cacher.active_count\n```\n\nYou may want to flush cache on the number of active users changed. It can be done by setting [`expire_by`](#expire_by). In this case, `User#last_login_at` means flushing the cache when a user's `last_login_at` is changed (by save, update, create, destroy or delete).\n\n### Example 2: Cache the number of users\n\nIn this example, the cache should be cleaned on user `destroyed`, or new user `created`, but not on user `updated`. You can specify the cleaning callback to only fire on certain events by [`on`](#on).\n\n```rb\nclass User \u003c ActiveRecord::Base\n  cache_at :count, -\u003e{ count }, expire_by: 'User', on: [:create, :destroy]\nend\n\n@count = User.cacher.count\n```\n\n### Example 3: Access the cacher from a model instance\n\nYou could use the cacher from the instance scope, e.g. `user.cacher`, instead of `User.cacher`. The difference is that the `binding` of query lambda is changed. In this example, you can write the query as `posts.exists?` which is in instance scope. The binding of the lambda is `user`, not `User`, so that it accesses `posts` method of `user`.\n\n```rb\n# Access cacher from instance\nclass User \u003c ActiveRecord::Base\n  has_many :posts\n  cache_at :has_post?, -\u003e{ posts.exists? }, expire_by: :posts\nend\n\nuser = User.take\ndo_something if user.cacher.has_post?\n```\n\n```rb\n# Access cacher from class (It's useful when you don't want to do an extra query)\nclass User \u003c ActiveRecord::Base\n  has_many :posts\n  cache_at :has_post?, -\u003e(id){ Post.where(user_id: id).exists? }, expire_by: :posts\nend\n\nuser_id = 1\ndo_something if User.cacher_at(user_id).has_post?\n```\n\nIn this example, the cache should be cleaned when the `posts` of the user is changed. If you set `expire_by` to the association: `:posts`, it will do all the work for you (It actually sets [`expire_by`](#expire_by) to `Post#user_id` and [`foreign_key`](#foreign_key), which is needed for backtracing the user id from post, to `:user_id`).\n\n\n### Example 4: Pass an argument to the query lambda\n\nYou can also cache the result of outer service.`email_valid?` doesn't match an association or an attribute, so by default, the cache will not be cleaned by any changes.\n\n```rb\nclass User \u003c ActiveRecord::Base\n  cache_at :email_valid?, -\u003e(email){ ValidEmail2::Address.new(email).valid_mx? }\nend\n\nrender_error if not User.cacher_at('pearl@example.com').email_valid?\n```\n\nThe query lambda can have one parameter. You can pass variable to it by using `cacher_at`. For example, `User.cacher_at(email)`.\n\n```rb\nclass User \u003c ActiveRecord::Base\n  cache_at :email_valid?, -\u003e(email){ ValidEmail2::Address.new(email).valid_mx? }, primary_key: :email\nend\n\nrender_error if not current_user.cacher.email_valid?\n```\n\nThe query lambda can also be accessed from instance cacher, but you have to set [`primary_key`](#primary_key). The primary key specifies which attribute should be passed to the parameter.\n\n### Example 5: Store all data in hash\n\nSometimes you may need to query multiple objects. Although the query results will be cached, the application still needs to query the cache server multiple times. If one communication takes 0.1 ms, 1000 communications will take 100ms! For example:\n\n```rb\nclass Skill \u003c ActiveRecord::Base\n  cache_at :atk_power\nend\n\n# This will retrieve the data from cache servers multiple times.\n@attack = skill_ids.inject(0){|sum, id| sum + Skill.cacher_at(id).atk_power }\n```\n\nOne solution is to store a lookup table into the cache, so that only one cache object is stored. This will allow you to retrieve all of the needed data in one query.\n\n```rb\nclass Skill \u003c ActiveRecord::Base\n  cache_at :atk_powers, -\u003e{ pluck(:id, :atk_power).to_h }, expire_by: 'Skill#atk_power'\nend\n\n# This will retrieve the data from cache servers only 1 times.\n@attack = skill_ids.inject(0){|sum, id| sum + Skill.cacher.atk_powers[id] }\n```\n\n### Example 6: Clean the cache manually\n\nSometimes it is necessary to maintain the cache manually (For example, after calling `update_all`, `delete_all` or `import` records without calling callbacks).\n\n```rb\nclass User \u003c ActiveRecord::Base\n  has_one :profile\n  cache_at :profile\nend\n\n# clean the cache by name\ncurrent_user.cacher.clean(:profile)\n\n# or calling the clean_* method\ncurrent_user.cacher.clean_profile\n\n# clean the cache without loading model\nUser.cacher_at(user_id).clean_profile\n```\n\n### Example 7: Peek the data stored in cache\n\nIf you only want to check the cached objects, but don't want it to load them from the database automatically when there is no cache, you can use `peek` method on `cacher`.\n\n```rb\nclass User \u003c ActiveRecord::Base\n  has_one :profile\n  cache_at :profile\nend\n\n# peek the cache by name\ncurrent_user.cacher.peek(:profile)\n\n# or calling the peek_* method\ncurrent_user.cacher.peek_profile\n\n# peek the cache without loading model\nUser.cacher_at(user_id).peek_profile\n```\n\n\n## Smart Caching\n\n### Multi-level Cache\nThere is multi-level cache in order to increase the speed of data access.\n\n1. RequestStore\n2. Rails.cache\n3. Association Cache\n4. Database\n\n`RequestStore` is used to make sure the same object will not be loaded from cache twice, since the data transfer between `Cache` and `Application` consumes time.\n\n`Association Cache` prevents preloaded objects being loaded again.\n\nFor example:\n```rb\nuser = User.includes(:posts).take\nuser.cacher.posts # =\u003e no query will be made even on cache miss.\n```\n\n## Convenient syntax sugar for caching ActiveRecord\n\n### Caching Associations\n```rb\nclass User \u003c ActiveRecord::Base\n  has_one :profile\n  cache_at :profile\nend\n\n@profile = current_user.cacher.profile\n\n# directly get profile without loading user.\n@profile = User.cacher_at(user_id).profile\n```\n\n### Caching Self\n\nCache self by id:\n```rb\nclass User \u003c ActiveRecord::Base\n  cache_self\nend\n\n@user = User.cacher.find_by(id: user_id)\n\n# peek cache\nUser.cacher.peek_by(id: user_id)\n\n# clean cache\nUser.cacher.clean_by(id: user_id)\n```\n\nAlso support caching self by other columns:\n```rb\nclass User \u003c ActiveRecord::Base\n  cache_self by: :account\nend\n\n@user = User.cacher.find_by(account: 'khiav')\n\n# peek cache\nUser.cacher.peek_by(account: 'khiav')\n\n# clean cache\nUser.cacher.clean_by(account: 'khiav')\n```\n\n### Caching Attributes\n\n```rb\nclass Profile \u003c ActiveRecord::Base\n  cache_at :point\nend\n\n@point = Profile.cacher_at(profile_id).point\n```\n\n## Options\n\n### :expire_by\n\nMonitor on the specific model. Clean the cached objects if targets are changed.\n\n  - If empty, e.g. `nil` or `''`: Monitoring nothing.\n\n  - If string, e.g. `User`: Monitoring all attributes of `User`.\n\n  - If string with keyword `#`, e.g. `User#last_login_in_at`: Monitoring only an specific attribute.\n\n  - If symbol, e.g. `:posts`: Monitoring on the association. It will monitor all attributes of `Post` and set the `foreign_key'.\n\n  - The default value depends on the `name`. If `name`:\n\n  - Is an association, monitoring the association klass\n\n  - Is an attribute, monitoring current klass and the attribute name\n\n  - In other cases, monitoring nothing\n\n### :on\n\n Fire changes only by a certain action with the `on` option. Like the same option of [after_commit](https://apidock.com/rails/ActiveRecord/Transactions/ClassMethods/after_commit).\n\n  - if `:create`: Clean the cache only on new record is created, e.g. `Model.create`.\n\n  - if `:update`: Clean the cache only on the record is updated, e.g. `model.update`.\n\n  - if `:destroy`: Clean the cache only on the record id destroyed, e.g. `model.destroy`, `model.delete`.\n\n  - if `array`, e.g. `[:create, :update]`: Clean the cache by any of specified actions.\n\n  - Default value is `[:create, :update, :destroy]`\n\n### :foreign_key\n\n- Is needed only for caching assoication\n\n- Does not need to be set if [`expire_by`](#expire_by) is set to monitor association.\n\n- Is used for backtracing the cache key from cached objects. For example, it is used if `user` has_many `posts`, and `posts` is cached by user.id. If the post is changed, the column it is going to target must be specified so that the post can clean the cache at user (In this example mentioned, the column was `user_id`).\n\n- Has the default value `:id`.\n\n- Will be automatically determined if [`expire_by`](#expire_by) is symbol\n\n### :primary_key\n\n- Determine which column is going to pass to the query lambda, and to be part of the cache key.\u003cbr\u003e\n  For example:\n  \n  - **User.cache_at :arbitrary, -\u003e(id){ id }** \n  \n    The cache key will be `active_model_cachers_User_at_arbitrary_#{user.id}`\n    \n  - **User.cache_at :arbitrary, -\u003e(email){ email }, primary_key: :email** \n  \n    The cache key will be `active_model_cachers_User_at_arbitrary_#{user.email}`\n\n- Has the default value `:id`.\n\n## Future works\n\n- [ ] caching polymorphic associations\n- [ ] non-unique secondary indexes\n- [ ] caching attributes by multiple keys\n- [ ] testing counter cache\n- [ ] testing has_many through\n- [ ] testing has_and_belongs_to_many\n\n## Development\n\nAfter checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.\n\nTo install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb` before running `bundle exec rake release` (This command will create a git tag for the version, push the git commits, tags and the `.gem` files to rubygems.org).\n\n## Contributing\n\nBug reports and pull requests are welcome on GitHub at https://github.com/khiav223577/active_model_cachers. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.\n\n\n## License\n\nThe gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkhiav223577%2Factive_model_cachers","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkhiav223577%2Factive_model_cachers","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkhiav223577%2Factive_model_cachers/lists"}