active_model_cachers 2.1.3 → 2.1.8

Sign up to get free protection for your applications and to get access to all the features.
Files changed (36) hide show
  1. checksums.yaml +4 -4
  2. data/.github/workflows/ruby.yml +59 -0
  3. data/.gitignore +9 -9
  4. data/CHANGELOG.md +71 -50
  5. data/CODE_OF_CONDUCT.md +48 -48
  6. data/LICENSE.txt +21 -21
  7. data/README.md +399 -353
  8. data/Rakefile +10 -10
  9. data/active_model_cachers.gemspec +45 -38
  10. data/bin/console +14 -14
  11. data/bin/setup +8 -8
  12. data/gemfiles/3.2.gemfile +11 -11
  13. data/gemfiles/4.2.gemfile +11 -11
  14. data/gemfiles/5.0.gemfile +11 -11
  15. data/gemfiles/5.1.gemfile +11 -11
  16. data/gemfiles/5.2.gemfile +11 -11
  17. data/gemfiles/6.0.gemfile +11 -0
  18. data/lib/active_model_cachers.rb +11 -0
  19. data/lib/active_model_cachers/active_record/attr_model.rb +124 -103
  20. data/lib/active_model_cachers/active_record/cacher.rb +97 -96
  21. data/lib/active_model_cachers/active_record/extension.rb +119 -106
  22. data/lib/active_model_cachers/active_record/global_callbacks.rb +67 -59
  23. data/lib/active_model_cachers/cache_service.rb +151 -134
  24. data/lib/active_model_cachers/cache_service_factory.rb +55 -55
  25. data/lib/active_model_cachers/column_value_cache.rb +47 -46
  26. data/lib/active_model_cachers/config.rb +6 -6
  27. data/lib/active_model_cachers/false_object.rb +5 -5
  28. data/lib/active_model_cachers/hook/associations.rb +43 -43
  29. data/lib/active_model_cachers/hook/dependencies.rb +38 -38
  30. data/lib/active_model_cachers/hook/on_model_delete.rb +29 -29
  31. data/lib/active_model_cachers/nil_object.rb +5 -5
  32. data/lib/active_model_cachers/{active_record → patches}/patch_rails_3.rb +49 -49
  33. data/lib/active_model_cachers/patches/uninitialized_attribute.rb +9 -0
  34. data/lib/active_model_cachers/version.rb +4 -4
  35. metadata +31 -13
  36. data/.travis.yml +0 -26
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 22fbf696d9d01bea8d59d1c885ef7e0724bc46894d263ae0bd59023fcbf3d034
4
- data.tar.gz: f4b2166e69e896992e3fe0352201473faec0050f40253ace399a64af35ff8e71
3
+ metadata.gz: d6b20ee17233cdbe0fc3767bcdabc67b99005bfc7659d03a95e91b9a5986f4c6
4
+ data.tar.gz: da51039d678e2b34f079ba80651329663b8c00939217e5bc9a43a7188f655127
5
5
  SHA512:
6
- metadata.gz: 2c397c8098e6190ee501b91794bdadde52d561560cb1916c45a1da3ae60b24c1b7137b7cb0ebfe49ca5d9dc760e7052345dc4d9930e53face0be7e57bc831ad4
7
- data.tar.gz: 2ddab829f8dbe887e5757d3a674a9468b9811fe0f363a27bf548d55a7b8b5ffd22c0e05e41f49e0e6a41e6277fd6480f8c22fd1627ed7e4f7c8d7cf08163e986
6
+ metadata.gz: ee865db83bbbb296579526583a20880fe0533bb9d910c289661b228e03bc1c39bd959b54406a7574e83ada286eefc0b3fb0383d9b935c1cf609894615f010a84
7
+ data.tar.gz: 368eff3e92b1e17639e24d271153470ea676d2043ced5d2166e1ea93dda0a6799277932be301fdf826f4897095653c7807899e428bb9461a7d1d99b67d47ef5a
@@ -0,0 +1,59 @@
1
+ name: Ruby
2
+
3
+ on:
4
+ push:
5
+ paths-ignore:
6
+ - 'README.md'
7
+ - 'CHANGELOG.md'
8
+ pull_request:
9
+ branches: [ master ]
10
+ paths-ignore:
11
+ - 'README.md'
12
+ - 'CHANGELOG.md'
13
+
14
+ jobs:
15
+ test:
16
+ runs-on: ubuntu-latest
17
+ name: Test
18
+ if: "contains(github.event.commits[0].message, '[ci skip]') == false"
19
+ strategy:
20
+ fail-fast: false
21
+ matrix:
22
+ ruby:
23
+ - 2.2
24
+ - 2.6
25
+ - 2.7
26
+ gemfile:
27
+ - 3.2.gemfile
28
+ - 4.2.gemfile
29
+ - 5.0.gemfile
30
+ - 5.1.gemfile
31
+ - 5.2.gemfile
32
+ - 6.0.gemfile
33
+ exclude:
34
+ - gemfile: 3.2.gemfile
35
+ ruby: 2.6
36
+ - gemfile: 3.2.gemfile
37
+ ruby: 2.7
38
+ - gemfile: 4.2.gemfile
39
+ ruby: 2.7
40
+ - gemfile: 6.0.gemfile
41
+ ruby: 2.2
42
+ env:
43
+ BUNDLE_GEMFILE: "gemfiles/${{ matrix.gemfile }}"
44
+
45
+ steps:
46
+ - name: Checkout
47
+ uses: actions/checkout@v2
48
+ - name: Setup Ruby
49
+ uses: ruby/setup-ruby@v1
50
+ with:
51
+ ruby-version: ${{ matrix.ruby }}
52
+ bundler-cache: true # runs 'bundle install' and caches installed gems automatically
53
+ - name: Run tests
54
+ run: bundle exec rake
55
+ - name: Publish code coverage
56
+ if: ${{ success() }}
57
+ uses: paambaati/codeclimate-action@v2.7.5
58
+ env:
59
+ CC_TEST_REPORTER_ID: ${{ secrets.CC_TEST_REPORTER_ID }}
data/.gitignore CHANGED
@@ -1,9 +1,9 @@
1
- /.bundle/
2
- /.yardoc
3
- /Gemfile.lock
4
- /_yardoc/
5
- /coverage/
6
- /doc/
7
- /pkg/
8
- /spec/reports/
9
- /tmp/
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
data/CHANGELOG.md CHANGED
@@ -1,50 +1,71 @@
1
- ## Change Log
2
-
3
- ### [v2.1.2](https://github.com/khiav223577/active_model_cachers/compare/v2.1.1...v2.1.2) 2018/06/01
4
- - [#37](https://github.com/khiav223577/active_model_cachers/pull/37) Fix: ModelName cant be referred to in development (@khiav223577)
5
-
6
- ### [v2.1.1](https://github.com/khiav223577/active_model_cachers/compare/v2.1.0...v2.1.1) 2018/05/25
7
- - [#35](https://github.com/khiav223577/active_model_cachers/pull/35) Preventing registering same callbacks in some cases (@khiav223577)
8
- - [#34](https://github.com/khiav223577/active_model_cachers/pull/34) Enhance - automatically clean cache when `#touch` (@ff2248)
9
- - [#33](https://github.com/khiav223577/active_model_cachers/pull/33) [Enhance] Code Climate Gem Deprecation (@berniechiu)
10
-
11
- ### [v2.1.0](https://github.com/khiav223577/active_model_cachers/compare/v2.0.3...v2.1.0) 2018/05/18
12
- - [#32](https://github.com/khiav223577/active_model_cachers/pull/32) Add test cases to test "store all data in hash" (@khiav223577)
13
- - [#31](https://github.com/khiav223577/active_model_cachers/pull/31) Change the syntax of getting self from cache (@khiav223577)
14
- - [#29](https://github.com/khiav223577/active_model_cachers/pull/29) test assigning association (@khiav223577)
15
-
16
- ### [v2.0.3](https://github.com/khiav223577/active_model_cachers/compare/v2.0.2...v2.0.3) 2018/05/14
17
- - [#28](https://github.com/khiav223577/active_model_cachers/pull/28) No need to dump all association caches (@khiav223577)
18
-
19
- ### [v2.0.2](https://github.com/khiav223577/active_model_cachers/compare/v2.0.1...v2.0.2) 2018/05/14
20
- - [#27](https://github.com/khiav223577/active_model_cachers/pull/27) [Fix] will send query even if has one association is cached (@khiav223577)
21
-
22
- ### [v2.0.1](https://github.com/khiav223577/active_model_cachers/compare/v2.0.0...v2.0.1) 2018/05/13
23
- - [#26](https://github.com/khiav223577/active_model_cachers/pull/26) Prevent infinite loop if someone override default associations' method (@khiav223577)
24
-
25
- ### v2.0.0 2018/05/13
26
- - [#25](https://github.com/khiav223577/active_model_cachers/pull/25) Support cache self by other column (@khiav223577)
27
- - [#24](https://github.com/khiav223577/active_model_cachers/pull/24) Support cleaning the cache manually (@khiav223577)
28
- - [#23](https://github.com/khiav223577/active_model_cachers/pull/23) use loaded model if possible to prevent extra queries (@khiav223577)
29
- - [#22](https://github.com/khiav223577/active_model_cachers/pull/22) Support caching result from outer service (@khiav223577)
30
- - [#21](https://github.com/khiav223577/active_model_cachers/pull/21) Support writing query in instance scope (@khiav223577)
31
- - [#20](https://github.com/khiav223577/active_model_cachers/pull/20) instance cacher (@khiav223577)
32
- - [#19](https://github.com/khiav223577/active_model_cachers/pull/19) Pass model to `delete` method to prevent an extra query (@khiav223577)
33
- - [#18](https://github.com/khiav223577/active_model_cachers/pull/18) [Test] show all sql queries if query count doesn't equal to expected count. (@khiav223577)
34
- - [#17](https://github.com/khiav223577/active_model_cachers/pull/17) Support cache at has_many association II - add test cases (@khiav223577)
35
- - [#16](https://github.com/khiav223577/active_model_cachers/pull/16) Support cache at has_many association I (@khiav223577)
36
- - [#15](https://github.com/khiav223577/active_model_cachers/pull/15) Adjust file structures (@khiav223577)
37
- - [#14](https://github.com/khiav223577/active_model_cachers/pull/14) Support cache at belongs_to association (@khiav223577)
38
- - [#13](https://github.com/khiav223577/active_model_cachers/pull/13) Fix that cache not cleaned if foreign_key is not `id` and calling `mode.delete` (@khiav223577)
39
- - [#12](https://github.com/khiav223577/active_model_cachers/pull/12) [Refactor] move the active_record extension to proper directory (@khiav223577)
40
- - [#11](https://github.com/khiav223577/active_model_cachers/pull/11) Fix id problem by specify foreign_key manually (@khiav223577)
41
- - [#10](https://github.com/khiav223577/active_model_cachers/pull/10) cache on falsy result (@khiav223577)
42
- - [#9](https://github.com/khiav223577/active_model_cachers/pull/9) Fix that all models cache with same id will be cleaned if any of one is cleaned (@khiav223577)
43
- - [#8](https://github.com/khiav223577/active_model_cachers/pull/8) allow developer to specify whether the cache should expire (@khiav223577)
44
- - [#7](https://github.com/khiav223577/active_model_cachers/pull/7) custom query which allow you to specify how to expire the cache by `expire_by` option (@khiav223577)
45
- - [#6](https://github.com/khiav223577/active_model_cachers/pull/6) test cache self (@khiav223577)
46
- - [#5](https://github.com/khiav223577/active_model_cachers/pull/5) Deal with delete, dependent: :delete that do not fire after_commit callback (@khiav223577)
47
- - [#4](https://github.com/khiav223577/active_model_cachers/pull/4) split test cases to several files and refactor the code (@khiav223577)
48
- - [#3](https://github.com/khiav223577/active_model_cachers/pull/3) Safer cache mechanism: Prevent cache from being left over if someone forgets to write `cache_self` (@khiav223577)
49
- - [#2](https://github.com/khiav223577/active_model_cachers/pull/2) Adjust usage (@khiav223577)
50
- - [#1](https://github.com/khiav223577/active_model_cachers/pull/1) use after_commit hook to expire cached associations (@khiav223577)
1
+ ## Change Log
2
+
3
+ ### [v2.1.7](https://github.com/khiav223577/active_model_cachers/compare/v2.1.6...v2.1.7) 2019/09/24
4
+ - [#50](https://github.com/khiav223577/active_model_cachers/pull/50) Support Rails 6.0 (@khiav223577)
5
+ - [#49](https://github.com/khiav223577/active_model_cachers/pull/49) Lock sqlite3 version to 1.3.x (@khiav223577)
6
+
7
+ ### [v2.1.6](https://github.com/khiav223577/active_model_cachers/compare/v2.1.5...v2.1.6) 2019/01/20
8
+ - [#48](https://github.com/khiav223577/active_model_cachers/pull/48) Support `has_and_belongs_to_many` && `has_many through` (@khiav223577)
9
+ - [#47](https://github.com/khiav223577/active_model_cachers/pull/47) Fix: broken test cases after bundler 2.0 was released (@khiav223577)
10
+ - [#46](https://github.com/khiav223577/active_model_cachers/pull/46) fix typo in README (@Fatmylin)
11
+
12
+ ### [v2.1.5](https://github.com/khiav223577/active_model_cachers/compare/v2.1.4...v2.1.5) 2018/08/03
13
+ - [#44](https://github.com/khiav223577/active_model_cachers/pull/44) should fire an extra query if the attribute used to clean cache is not selected (@khiav223577)
14
+ - [#45](https://github.com/khiav223577/active_model_cachers/pull/45) lazily add global callbacks to ActiveRecord::Base (@khiav223577)
15
+ - [#43](https://github.com/khiav223577/active_model_cachers/pull/43) Improve the structure of README. (@cybersol795)
16
+
17
+ ### [v2.1.4](https://github.com/khiav223577/active_model_cachers/compare/v2.1.3...v2.1.4) 2018/06/14
18
+ - [#41](https://github.com/khiav223577/active_model_cachers/pull/41) Fix: binding problem (@khiav223577)
19
+ - [#40](https://github.com/khiav223577/active_model_cachers/pull/40) [Refactor] Solve warnings (@khiav223577)
20
+
21
+ ### [v2.1.3](https://github.com/khiav223577/active_model_cachers/compare/v2.1.2...v2.1.3) 2018/06/07
22
+ - [#38](https://github.com/khiav223577/active_model_cachers/pull/38) Fix: Eager-loaded models will not register `after_commit` callback (@khiav223577)
23
+
24
+ ### [v2.1.2](https://github.com/khiav223577/active_model_cachers/compare/v2.1.1...v2.1.2) 2018/06/01
25
+ - [#37](https://github.com/khiav223577/active_model_cachers/pull/37) Fix: ModelName cant be referred to in development (@khiav223577)
26
+
27
+ ### [v2.1.1](https://github.com/khiav223577/active_model_cachers/compare/v2.1.0...v2.1.1) 2018/05/25
28
+ - [#35](https://github.com/khiav223577/active_model_cachers/pull/35) Preventing registering same callbacks in some cases (@khiav223577)
29
+ - [#34](https://github.com/khiav223577/active_model_cachers/pull/34) Enhance - automatically clean cache when `#touch` (@ff2248)
30
+ - [#33](https://github.com/khiav223577/active_model_cachers/pull/33) [Enhance] Code Climate Gem Deprecation (@berniechiu)
31
+
32
+ ### [v2.1.0](https://github.com/khiav223577/active_model_cachers/compare/v2.0.3...v2.1.0) 2018/05/18
33
+ - [#32](https://github.com/khiav223577/active_model_cachers/pull/32) Add test cases to test "store all data in hash" (@khiav223577)
34
+ - [#31](https://github.com/khiav223577/active_model_cachers/pull/31) Change the syntax of getting self from cache (@khiav223577)
35
+ - [#29](https://github.com/khiav223577/active_model_cachers/pull/29) test assigning association (@khiav223577)
36
+
37
+ ### [v2.0.3](https://github.com/khiav223577/active_model_cachers/compare/v2.0.2...v2.0.3) 2018/05/14
38
+ - [#28](https://github.com/khiav223577/active_model_cachers/pull/28) No need to dump all association caches (@khiav223577)
39
+
40
+ ### [v2.0.2](https://github.com/khiav223577/active_model_cachers/compare/v2.0.1...v2.0.2) 2018/05/14
41
+ - [#27](https://github.com/khiav223577/active_model_cachers/pull/27) [Fix] will send query even if has one association is cached (@khiav223577)
42
+
43
+ ### [v2.0.1](https://github.com/khiav223577/active_model_cachers/compare/v2.0.0...v2.0.1) 2018/05/13
44
+ - [#26](https://github.com/khiav223577/active_model_cachers/pull/26) Prevent infinite loop if someone override default associations' method (@khiav223577)
45
+
46
+ ### [v2.0.0](https://github.com/khiav223577/active_model_cachers/compare/v1.0.0...v2.0.0) 2018/05/13
47
+ - [#25](https://github.com/khiav223577/active_model_cachers/pull/25) Support cache self by other column (@khiav223577)
48
+ - [#24](https://github.com/khiav223577/active_model_cachers/pull/24) Support cleaning the cache manually (@khiav223577)
49
+ - [#23](https://github.com/khiav223577/active_model_cachers/pull/23) use loaded model if possible to prevent extra queries (@khiav223577)
50
+ - [#22](https://github.com/khiav223577/active_model_cachers/pull/22) Support caching result from outer service (@khiav223577)
51
+ - [#21](https://github.com/khiav223577/active_model_cachers/pull/21) Support writing query in instance scope (@khiav223577)
52
+ - [#20](https://github.com/khiav223577/active_model_cachers/pull/20) instance cacher (@khiav223577)
53
+ - [#19](https://github.com/khiav223577/active_model_cachers/pull/19) Pass model to `delete` method to prevent an extra query (@khiav223577)
54
+ - [#18](https://github.com/khiav223577/active_model_cachers/pull/18) [Test] show all sql queries if query count doesn't equal to expected count. (@khiav223577)
55
+ - [#17](https://github.com/khiav223577/active_model_cachers/pull/17) Support cache at has_many association II - add test cases (@khiav223577)
56
+ - [#16](https://github.com/khiav223577/active_model_cachers/pull/16) Support cache at has_many association I (@khiav223577)
57
+ - [#15](https://github.com/khiav223577/active_model_cachers/pull/15) Adjust file structures (@khiav223577)
58
+ - [#14](https://github.com/khiav223577/active_model_cachers/pull/14) Support cache at belongs_to association (@khiav223577)
59
+ - [#13](https://github.com/khiav223577/active_model_cachers/pull/13) Fix that cache not cleaned if foreign_key is not `id` and calling `mode.delete` (@khiav223577)
60
+ - [#12](https://github.com/khiav223577/active_model_cachers/pull/12) [Refactor] move the active_record extension to proper directory (@khiav223577)
61
+ - [#11](https://github.com/khiav223577/active_model_cachers/pull/11) Fix id problem by specify foreign_key manually (@khiav223577)
62
+ - [#10](https://github.com/khiav223577/active_model_cachers/pull/10) cache on falsy result (@khiav223577)
63
+ - [#9](https://github.com/khiav223577/active_model_cachers/pull/9) Fix that all models cache with same id will be cleaned if any of one is cleaned (@khiav223577)
64
+ - [#8](https://github.com/khiav223577/active_model_cachers/pull/8) allow developer to specify whether the cache should expire (@khiav223577)
65
+ - [#7](https://github.com/khiav223577/active_model_cachers/pull/7) custom query which allow you to specify how to expire the cache by `expire_by` option (@khiav223577)
66
+ - [#6](https://github.com/khiav223577/active_model_cachers/pull/6) test cache self (@khiav223577)
67
+ - [#5](https://github.com/khiav223577/active_model_cachers/pull/5) Deal with delete, dependent: :delete that do not fire after_commit callback (@khiav223577)
68
+ - [#4](https://github.com/khiav223577/active_model_cachers/pull/4) split test cases to several files and refactor the code (@khiav223577)
69
+ - [#3](https://github.com/khiav223577/active_model_cachers/pull/3) Safer cache mechanism: Prevent cache from being left over if someone forgets to write `cache_self` (@khiav223577)
70
+ - [#2](https://github.com/khiav223577/active_model_cachers/pull/2) Adjust usage (@khiav223577)
71
+ - [#1](https://github.com/khiav223577/active_model_cachers/pull/1) use after_commit hook to expire cached associations (@khiav223577)
data/CODE_OF_CONDUCT.md CHANGED
@@ -1,49 +1,49 @@
1
- # Contributor Code of Conduct
2
-
3
- As contributors and maintainers of this project, and in the interest of
4
- fostering an open and welcoming community, we pledge to respect all people who
5
- contribute through reporting issues, posting feature requests, updating
6
- documentation, submitting pull requests or patches, and other activities.
7
-
8
- We are committed to making participation in this project a harassment-free
9
- experience for everyone, regardless of level of experience, gender, gender
10
- identity and expression, sexual orientation, disability, personal appearance,
11
- body size, race, ethnicity, age, religion, or nationality.
12
-
13
- Examples of unacceptable behavior by participants include:
14
-
15
- * The use of sexualized language or imagery
16
- * Personal attacks
17
- * Trolling or insulting/derogatory comments
18
- * Public or private harassment
19
- * Publishing other's private information, such as physical or electronic
20
- addresses, without explicit permission
21
- * Other unethical or unprofessional conduct
22
-
23
- Project maintainers have the right and responsibility to remove, edit, or
24
- reject comments, commits, code, wiki edits, issues, and other contributions
25
- that are not aligned to this Code of Conduct, or to ban temporarily or
26
- permanently any contributor for other behaviors that they deem inappropriate,
27
- threatening, offensive, or harmful.
28
-
29
- By adopting this Code of Conduct, project maintainers commit themselves to
30
- fairly and consistently applying these principles to every aspect of managing
31
- this project. Project maintainers who do not follow or enforce the Code of
32
- Conduct may be permanently removed from the project team.
33
-
34
- This code of conduct applies both within project spaces and in public spaces
35
- when an individual is representing the project or its community.
36
-
37
- Instances of abusive, harassing, or otherwise unacceptable behavior may be
38
- reported by contacting a project maintainer at mrtmrt15xn@yahoo.com.tw. All
39
- complaints will be reviewed and investigated and will result in a response that
40
- is deemed necessary and appropriate to the circumstances. Maintainers are
41
- obligated to maintain confidentiality with regard to the reporter of an
42
- incident.
43
-
44
- This Code of Conduct is adapted from the [Contributor Covenant][homepage],
45
- version 1.3.0, available at
46
- [http://contributor-covenant.org/version/1/3/0/][version]
47
-
48
- [homepage]: http://contributor-covenant.org
1
+ # Contributor Code of Conduct
2
+
3
+ As contributors and maintainers of this project, and in the interest of
4
+ fostering an open and welcoming community, we pledge to respect all people who
5
+ contribute through reporting issues, posting feature requests, updating
6
+ documentation, submitting pull requests or patches, and other activities.
7
+
8
+ We are committed to making participation in this project a harassment-free
9
+ experience for everyone, regardless of level of experience, gender, gender
10
+ identity and expression, sexual orientation, disability, personal appearance,
11
+ body size, race, ethnicity, age, religion, or nationality.
12
+
13
+ Examples of unacceptable behavior by participants include:
14
+
15
+ * The use of sexualized language or imagery
16
+ * Personal attacks
17
+ * Trolling or insulting/derogatory comments
18
+ * Public or private harassment
19
+ * Publishing other's private information, such as physical or electronic
20
+ addresses, without explicit permission
21
+ * Other unethical or unprofessional conduct
22
+
23
+ Project maintainers have the right and responsibility to remove, edit, or
24
+ reject comments, commits, code, wiki edits, issues, and other contributions
25
+ that are not aligned to this Code of Conduct, or to ban temporarily or
26
+ permanently any contributor for other behaviors that they deem inappropriate,
27
+ threatening, offensive, or harmful.
28
+
29
+ By adopting this Code of Conduct, project maintainers commit themselves to
30
+ fairly and consistently applying these principles to every aspect of managing
31
+ this project. Project maintainers who do not follow or enforce the Code of
32
+ Conduct may be permanently removed from the project team.
33
+
34
+ This code of conduct applies both within project spaces and in public spaces
35
+ when an individual is representing the project or its community.
36
+
37
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
38
+ reported by contacting a project maintainer at mrtmrt15xn@yahoo.com.tw. All
39
+ complaints will be reviewed and investigated and will result in a response that
40
+ is deemed necessary and appropriate to the circumstances. Maintainers are
41
+ obligated to maintain confidentiality with regard to the reporter of an
42
+ incident.
43
+
44
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
45
+ version 1.3.0, available at
46
+ [http://contributor-covenant.org/version/1/3/0/][version]
47
+
48
+ [homepage]: http://contributor-covenant.org
49
49
  [version]: http://contributor-covenant.org/version/1/3/0/
data/LICENSE.txt CHANGED
@@ -1,21 +1,21 @@
1
- The MIT License (MIT)
2
-
3
- Copyright (c) 2016 khiav reoy
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in
13
- all copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
- THE SOFTWARE.
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2016 khiav reoy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md CHANGED
@@ -1,353 +1,399 @@
1
- # ActiveModelCachers
2
-
3
- [![Gem Version](https://img.shields.io/gem/v/active_model_cachers.svg?style=flat)](http://rubygems.org/gems/active_model_cachers)
4
- [![Build Status](https://travis-ci.org/khiav223577/active_model_cachers.svg?branch=master)](https://travis-ci.org/khiav223577/active_model_cachers)
5
- [![RubyGems](http://img.shields.io/gem/dt/active_model_cachers.svg?style=flat)](http://rubygems.org/gems/active_model_cachers)
6
- [![Code Climate](https://codeclimate.com/github/khiav223577/active_model_cachers/badges/gpa.svg)](https://codeclimate.com/github/khiav223577/active_model_cachers)
7
- [![Test Coverage](https://codeclimate.com/github/khiav223577/active_model_cachers/badges/coverage.svg)](https://codeclimate.com/github/khiav223577/active_model_cachers/coverage)
8
-
9
- Provide cachers to the model so that you could specify which you want to cache. Data will be cached at `Rails.cache` and also at application level via `RequestStore` to cache values between requests. Cachers will maintain cached objects and expire them when they are changed (including create, update, destroy, and even delete).
10
-
11
- - [Multi-level Cache](#multi-level-cache)
12
- - Do not pollute original ActiveModel API.
13
- - Support ActiveRecord 3, 4, 5.
14
- - High test coverage
15
-
16
-
17
- ## Compare with [identity_cache](https://github.com/Shopify/identity_cache)
18
-
19
- `active_model_cachers` allows you to specify what to cache and when to expire those caches. So that you could cache raw sql query results, time-consuming methods, responses of requests, and so on. It also supports AR associations / attibutes (has_many, has_one, belongs_to) and secondary indexes.
20
-
21
- `identity_cache` focuses on AR, and doesn't have the flexibility to specify the query. It has more features for caching AR associations / attibutes, such as caching attibutes by multiple keys, embedding associations to load data in one fetch, non-unique secondary indexes, and caching polymorphic associations, etc.
22
-
23
- There is also a difference worths mentioning, `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.
24
-
25
- ## Installation
26
-
27
- Add this line to your application's Gemfile:
28
-
29
- ```ruby
30
- gem 'active_model_cachers'
31
- ```
32
-
33
- And then execute:
34
-
35
- $ bundle
36
-
37
- Or install it yourself as:
38
-
39
- $ gem install active_model_cachers
40
-
41
- Add an initializer with this code to your project:
42
-
43
- ```rb
44
- ActiveModelCachers.config do |config|
45
- config.store = Rails.cache # specify where the cache will be stored
46
- end
47
- ```
48
-
49
- ## Usage
50
-
51
- ### Cache whatever you want by `cache_at` method
52
-
53
- `cache_at(name, query = nil, options = {})`
54
-
55
- Specify a cache on the model.
56
- - name: the attribute name.
57
- - query: how to get data on cache miss. It will be set automatically if the name match an association or an attribute.
58
- - options: see [here](#options)
59
-
60
- ### Asscess the cached attributes
61
-
62
- The `cacher` is defined as `class method` and `instance method` of Model. You could call the method and get the cacher instance, e.g. `User.cacher` or `user.cacher`. An attribute will define a method on cacher, cached attributes are asscessable via it, e.g. `user.cacher.the_attribute_name`.
63
-
64
-
65
- ### Basic Example
66
- ```rb
67
- class User < ActiveRecord::Base
68
- cache_at :something_you_want_to_cache, ->{ get_the_data_on_cache_miss }
69
- end
70
-
71
- user.cacher.something_you_want_to_cache
72
- ```
73
-
74
-
75
- ## Examples
76
-
77
- ### Example 1: Cache the number of active user
78
-
79
- After specifying the name as `active_count` and how to get data when cache miss by lambda `User.active.count`.
80
- You could access the cached data by calling `active_count` method on the cacher, `User.cacher`.
81
-
82
- ```rb
83
- class User < ActiveRecord::Base
84
- scope :active, ->{ where('last_login_at > ?', 7.days.ago) }
85
-  cache_at :active_count, ->{ active.count }, expire_by: 'User#last_login_at'
86
- end
87
-
88
- @count = User.cacher.active_count
89
- ```
90
-
91
- You may want to flush cache on the number of active user changed. It can be done by simply 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 (whenever by save, update, create, destroy or delete).
92
-
93
- ### Example 2: Cache the number of user
94
-
95
- In this example, the cache should be cleaned on user `destroyed`, or new user `created`, but not on user `updated`. You could specify the cleaning callback to only fire on certain events by [`on`](#on).
96
-
97
- ```rb
98
- class User < ActiveRecord::Base
99
- cache_at :count, ->{ count }, expire_by: 'User', on: [:create, :destroy]
100
- end
101
-
102
- @count = User.cacher.count
103
- ```
104
-
105
- ### Example 3: Access the cacher from a model instance
106
-
107
- You could use the cacher from 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 could write the query as `posts.exists?` in that it's in instance scope, and the binding of the lambda is `user`, not `User`. So that it accesses `posts` method of `user`.
108
-
109
- ```rb
110
- class User < ActiveRecord::Base
111
- has_many :posts
112
- cache_at :has_post?, ->{ posts.exists? }, expire_by: :posts
113
- end
114
-
115
- do_something if current_user.cacher.has_post?
116
- ```
117
-
118
- In this example, the cache should be cleaned when the `posts` of the user changed. You could just set `expire_by` to the association: `:posts`, and then it will do all the works for you magically. (If you want know more details, it actually set [`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`)
119
-
120
-
121
- ### Example 4: Pass an argument to the query lambda.
122
-
123
- You could cache not only the query result of database but also the result of outer service. Becasue `email_valid?` doesn't match an association or an attribute, by default, the cache will not be cleaned by any changes.
124
-
125
- ```rb
126
- class User < ActiveRecord::Base
127
- cache_at :email_valid?, ->(email){ ValidEmail2::Address.new(email).valid_mx? }
128
- end
129
-
130
- render_error if not User.cacher_at('pearl@example.com').email_valid?
131
- ```
132
-
133
- The query lambda can have one parameter, you could pass variable to it by using `cacher_at`. For example, `User.cacher_at(email)`.
134
-
135
- ```rb
136
- class User < ActiveRecord::Base
137
- cache_at :email_valid?, ->(email){ ValidEmail2::Address.new(email).valid_mx? }, primary_key: :email
138
- end
139
-
140
- render_error if not current_user.cacher.email_valid?
141
- ```
142
-
143
- It can also be accessed from instance cacher. But you have to set [`primary_key`](#primary_key), which is needed to know which attribute should be passed to the parameter.
144
-
145
- ### Example 5: Store all data in hash
146
-
147
- Sometimes 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 take 0.1 ms, 1000 communications will take 100ms! For example:
148
-
149
- ```rb
150
- class Skill < ActiveRecord::Base
151
- cache_at :atk_power
152
- end
153
-
154
- # This will retrieve the data from cache servers multiple times.
155
- @attack = skill_ids.inject(0){|sum, id| sum + Skill.cacher_at(id).atk_power }
156
- ```
157
-
158
- One of the solution is that you could store a lookup table into cache, so that only one cache object is stored and you can retrieve all of the needed data in one query.
159
-
160
- ```rb
161
- class Skill < ActiveRecord::Base
162
- cache_at :atk_powers, ->{ pluck(:id, :atk_power).to_h }, expire_by: 'Skill#atk_power'
163
- end
164
-
165
- # This will retrieve the data from cache servers only 1 times.
166
- @attack = skill_ids.inject(0){|sum, id| sum + Skill.cacher.atk_powers[id] }
167
- ```
168
-
169
- ### Example 6: Clean the cache manually
170
-
171
- Sometimes it needs to maintain the cache manually. For example, after calling `update_all`, `delete_all` or `import` records without calling callbacks.
172
-
173
- ```rb
174
- class User < ActiveRecord::Base
175
- has_one :profile
176
- cache_at :profile
177
- end
178
-
179
- # clean the cache by name
180
- current_user.cacher.clean(:profile)
181
-
182
- # or calling the clean_* method
183
- current_user.cacher.clean_profile
184
-
185
- # clean the cache without loading model
186
- User.cacher_at(user_id).clean_profile
187
- ```
188
-
189
- ### Example 7: Peek the data stored in cache
190
-
191
- If you just want to check the cached objects, but don't want it to load from database automatically when there is no cache. You could use `peek` method on `cacher`.
192
-
193
- ```rb
194
- class User < ActiveRecord::Base
195
- has_one :profile
196
- cache_at :profile
197
- end
198
-
199
- # peek the cache by name
200
- current_user.cacher.peek(:profile)
201
-
202
- # or calling the peek_* method
203
- current_user.cacher.peek_profile
204
-
205
- # peek the cache without loading model
206
- User.cacher_at(user_id).peek_profile
207
- ```
208
-
209
-
210
- ## Smart Caching
211
-
212
- ### Multi-level Cache
213
- There is multi-level cache in order to make the speed of data access go faster.
214
-
215
- 1. RequestStore
216
- 2. Rails.cache
217
- 3. Association Cache
218
- 4. Database
219
-
220
- `RequestStore` is used to make sure same object will not loaded from cache twice, since the data transfer between `Cache` and `Application` still consumes time.
221
-
222
- `Association Cache` will be used to prevent preloaded objects being loaded again.
223
-
224
- For example:
225
- ```rb
226
- user = User.includes(:posts).take
227
- user.cacher.posts # => no query will be made even on cache miss.
228
- ```
229
-
230
- ## Convenient syntax sugar for caching ActiveRecord
231
-
232
- ### Caching Associations
233
- ```rb
234
- class User < ActiveRecord::Base
235
- has_one :profile
236
- cache_at :profile
237
- end
238
-
239
- @profile = current_user.cacher.profile
240
-
241
- # directly get profile without loading user.
242
- @profile = User.cacher_at(user_id).profile
243
- ```
244
-
245
- ### Caching Self
246
-
247
- Cache self by id.
248
- ```rb
249
- class User < ActiveRecord::Base
250
- cache_self
251
- end
252
-
253
- @user = User.cacher.find_by(id: user_id)
254
-
255
- # peek cache
256
- User.cacher.peek_by(id: user_id)
257
-
258
- # clean cache
259
- User.cacher.clean_by(id: user_id)
260
- ```
261
-
262
- Also support caching self by other columns.
263
- ```rb
264
- class User < ActiveRecord::Base
265
- cache_self by: :account
266
- end
267
-
268
- @user = User.cacher.find_by(account: 'khiav')
269
-
270
- # peek cache
271
- User.cacher.peek_by(account: 'khiav')
272
-
273
- # clean cache
274
- User.cacher.clean_by(account: 'khiav')
275
- ```
276
-
277
- ### Caching Attributes
278
-
279
- ```rb
280
- class Profile < ActiveRecord::Base
281
- cache_at :point
282
- end
283
-
284
- @point = Profile.cacher_at(profile_id).point
285
- ```
286
-
287
- ## Options
288
-
289
- ### :expire_by
290
-
291
- Monitor on the specific model. Clean the cached objects if target are changed.
292
-
293
- - if empty, e.g. `nil` or `''`: Monitoring nothing.
294
-
295
- - if string, e.g. `User`: Monitoring all attributes of `User`.
296
-
297
- - if string with keyword `#`, e.g. `User#last_login_in_at`: Monitoring only the specific attribute.
298
-
299
- - if symbol, e.g. `:posts`: Monitoring on the association. It will trying to do all the things for you, including monitoring all attributes of `Post` and set the `foreign_key`.
300
-
301
- - Default value depends on the `name`. If is an association, monitoring the association klass. If is an attribute, monitoring current klass and the attrribute name. If others, monitoring nothing.
302
-
303
- ### :on
304
-
305
- 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).
306
-
307
- - if `:create`: Clean the cache only on new record is created, e.g. `Model.create`.
308
-
309
- - if `:update`: Clean the cache only on the record is updated, e.g. `model.update`.
310
-
311
- - if `:destroy`: Clean the cache only on the record id destroyed, e.g. `model.destroy`, `model.delete`.
312
-
313
- - if `array`, e.g. `[:create, :update]`: Clean the cache by any of specified actions.
314
-
315
- - Default value is `[:create, :update, :destroy]`
316
-
317
- ### :foreign_key
318
-
319
- This option is needed only for caching assoication and need not to set if [`expire_by`](#expire_by) is set to monitor association. Used for backtracing the cache key from cached objects. For examle, if `user` has_many `posts`, and cached the `posts` by user.id. When a post is changed, it needs to know which column to use (in this example, `user_id`) to clean the cache at user.
320
-
321
- - Default value is `:id`
322
-
323
- - Will be automatically determined if [`expire_by`](#expire_by) is symbol.
324
-
325
- ### :primary_key
326
-
327
- This option is needed to know which attribute should be passed to the parameter when you are using instance cacher. For example, if a query, named `email_valid?`, uses `user.email` as parameter, and you call it from instance: `user.cacher.email_valid?`. You need to tell it to pass `user.email` instead of `user.id` as the argument.
328
-
329
- - Default value is `:id`
330
-
331
- ## Future works
332
-
333
- - [ ] caching polymorphic associations
334
- - [ ] non-unique secondary indexes
335
- - [ ] caching attibutes by multiple keys
336
- - [ ] testing counter cache
337
- - [ ] testing has_many through
338
- - [ ] testing has_and_belongs_to_many
339
-
340
- ## Development
341
-
342
- After 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.
343
-
344
- To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
345
-
346
- ## Contributing
347
-
348
- Bug 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.
349
-
350
-
351
- ## License
352
-
353
- The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
1
+ # ActiveModelCachers
2
+
3
+ [![Gem Version](https://img.shields.io/gem/v/active_model_cachers.svg?style=flat)](http://rubygems.org/gems/active_model_cachers)
4
+ [![Build Status](https://github.com/khiav223577/active_model_cachers/workflows/Ruby/badge.svg)](https://github.com/khiav223577/active_model_cachers/actions)
5
+ [![RubyGems](http://img.shields.io/gem/dt/active_model_cachers.svg?style=flat)](http://rubygems.org/gems/active_model_cachers)
6
+ [![Code Climate](https://codeclimate.com/github/khiav223577/active_model_cachers/badges/gpa.svg)](https://codeclimate.com/github/khiav223577/active_model_cachers)
7
+ [![Test Coverage](https://codeclimate.com/github/khiav223577/active_model_cachers/badges/coverage.svg)](https://codeclimate.com/github/khiav223577/active_model_cachers/coverage)
8
+
9
+ ActiveModelCachers 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).
10
+
11
+ ActiveModelCachers:
12
+
13
+ - Uses multiple levels of cache ([Multi-level Cache](#multi-level-cache))
14
+ - Does not pollute the original ActiveModel API
15
+ - Supports ActiveRecord 3.2, 4.2, 5.2, 6.0.
16
+ - Has high test coverage
17
+
18
+ ## Table of contents
19
+
20
+ 1. [Compare with identity_cache](#compare-with-identity_cache)
21
+ 2. [Installation](#installation)
22
+ 3. [Usage](#usage)
23
+ 4. [Examples](#examples)
24
+ 5. [Smart Caching](#smart-caching)
25
+ 6. [Convenient syntax sugar for caching ActiveRecord](#convenient-syntax-sugar-for-caching-activerecord)
26
+ 7. [Options](#options)
27
+ 8. [Future Works](#future-works)
28
+ 9. [Development](#development)
29
+ 10. [Contributing](#contributing)
30
+ 11. [License](#license)
31
+
32
+ ## Compare with [identity_cache](https://github.com/Shopify/identity_cache)
33
+
34
+ `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.
35
+
36
+ `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.
37
+
38
+ Another 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`.
39
+
40
+ ## Installation
41
+
42
+ To install active_model_cachers, add this line to your application's Gemfile:
43
+
44
+ ```ruby
45
+ gem 'active_model_cachers'
46
+ ```
47
+
48
+ Then execute:
49
+
50
+ $ bundle
51
+
52
+ Or install it yourself by executing:
53
+
54
+ $ gem install active_model_cachers
55
+
56
+ Add an initializer with this code to your project:
57
+
58
+ ```rb
59
+ ActiveModelCachers.config do |config|
60
+ config.store = Rails.cache # specify where the cache will be stored
61
+ end
62
+ ```
63
+
64
+ ## Usage
65
+
66
+ ### The `cache_at` method
67
+
68
+ Use the `cache_at` method to cache whatever you want. Specify a cache on the model:
69
+
70
+ `cache_at(name, query = nil, options = {})`
71
+
72
+ Parameters:
73
+ - name: the attribute name
74
+ - query: how to get data on cache miss. It will be set automatically if the name matches an association or an attribute.
75
+ - options: see [here](#options)
76
+
77
+ ### Access the cached attributes
78
+
79
+ To 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`).
80
+
81
+ ### Basic Example
82
+ ```rb
83
+ class User < ActiveRecord::Base
84
+ cache_at :something_you_want_to_cache, ->{ get_the_data_on_cache_miss }
85
+ end
86
+
87
+ user.cacher.something_you_want_to_cache
88
+ ```
89
+
90
+
91
+ ## Examples
92
+
93
+ ### Example 1: Cache the number of active users
94
+ Specify 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`.
95
+
96
+ ```rb
97
+ class User < ActiveRecord::Base
98
+ scope :active, ->{ where('last_login_at > ?', 7.days.ago) }
99
+  cache_at :active_count, ->{ active.count }, expire_by: 'User#last_login_at'
100
+ end
101
+
102
+ @count = User.cacher.active_count
103
+ ```
104
+
105
+ You 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).
106
+
107
+ ### Example 2: Cache the number of users
108
+
109
+ In 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).
110
+
111
+ ```rb
112
+ class User < ActiveRecord::Base
113
+ cache_at :count, ->{ count }, expire_by: 'User', on: [:create, :destroy]
114
+ end
115
+
116
+ @count = User.cacher.count
117
+ ```
118
+
119
+ ### Example 3: Access the cacher from a model instance
120
+
121
+ You 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`.
122
+
123
+ ```rb
124
+ # Access cacher from instance
125
+ class User < ActiveRecord::Base
126
+ has_many :posts
127
+ cache_at :has_post?, ->{ posts.exists? }, expire_by: :posts
128
+ end
129
+
130
+ user = User.take
131
+ do_something if user.cacher.has_post?
132
+ ```
133
+
134
+ ```rb
135
+ # Access cacher from class (It's useful when you don't want to do an extra query)
136
+ class User < ActiveRecord::Base
137
+ has_many :posts
138
+ cache_at :has_post?, ->(id){ Post.where(user_id: id).exists? }, expire_by: :posts
139
+ end
140
+
141
+ user_id = 1
142
+ do_something if User.cacher_at(user_id).has_post?
143
+ ```
144
+
145
+ In 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`).
146
+
147
+
148
+ ### Example 4: Pass an argument to the query lambda
149
+
150
+ You 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.
151
+
152
+ ```rb
153
+ class User < ActiveRecord::Base
154
+ cache_at :email_valid?, ->(email){ ValidEmail2::Address.new(email).valid_mx? }
155
+ end
156
+
157
+ render_error if not User.cacher_at('pearl@example.com').email_valid?
158
+ ```
159
+
160
+ The query lambda can have one parameter. You can pass variable to it by using `cacher_at`. For example, `User.cacher_at(email)`.
161
+
162
+ ```rb
163
+ class User < ActiveRecord::Base
164
+ cache_at :email_valid?, ->(email){ ValidEmail2::Address.new(email).valid_mx? }, primary_key: :email
165
+ end
166
+
167
+ render_error if not current_user.cacher.email_valid?
168
+ ```
169
+
170
+ The 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.
171
+
172
+ ### Example 5: Store all data in hash
173
+
174
+ Sometimes 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:
175
+
176
+ ```rb
177
+ class Skill < ActiveRecord::Base
178
+ cache_at :atk_power
179
+ end
180
+
181
+ # This will retrieve the data from cache servers multiple times.
182
+ @attack = skill_ids.inject(0){|sum, id| sum + Skill.cacher_at(id).atk_power }
183
+ ```
184
+
185
+ One 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.
186
+
187
+ ```rb
188
+ class Skill < ActiveRecord::Base
189
+ cache_at :atk_powers, ->{ pluck(:id, :atk_power).to_h }, expire_by: 'Skill#atk_power'
190
+ end
191
+
192
+ # This will retrieve the data from cache servers only 1 times.
193
+ @attack = skill_ids.inject(0){|sum, id| sum + Skill.cacher.atk_powers[id] }
194
+ ```
195
+
196
+ ### Example 6: Clean the cache manually
197
+
198
+ Sometimes it is necessary to maintain the cache manually (For example, after calling `update_all`, `delete_all` or `import` records without calling callbacks).
199
+
200
+ ```rb
201
+ class User < ActiveRecord::Base
202
+ has_one :profile
203
+ cache_at :profile
204
+ end
205
+
206
+ # clean the cache by name
207
+ current_user.cacher.clean(:profile)
208
+
209
+ # or calling the clean_* method
210
+ current_user.cacher.clean_profile
211
+
212
+ # clean the cache without loading model
213
+ User.cacher_at(user_id).clean_profile
214
+ ```
215
+
216
+ ### Example 7: Peek the data stored in cache
217
+
218
+ If 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`.
219
+
220
+ ```rb
221
+ class User < ActiveRecord::Base
222
+ has_one :profile
223
+ cache_at :profile
224
+ end
225
+
226
+ # peek the cache by name
227
+ current_user.cacher.peek(:profile)
228
+
229
+ # or calling the peek_* method
230
+ current_user.cacher.peek_profile
231
+
232
+ # peek the cache without loading model
233
+ User.cacher_at(user_id).peek_profile
234
+ ```
235
+
236
+
237
+ ## Smart Caching
238
+
239
+ ### Multi-level Cache
240
+ There is multi-level cache in order to increase the speed of data access.
241
+
242
+ 1. RequestStore
243
+ 2. Rails.cache
244
+ 3. Association Cache
245
+ 4. Database
246
+
247
+ `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.
248
+
249
+ `Association Cache` prevents preloaded objects being loaded again.
250
+
251
+ For example:
252
+ ```rb
253
+ user = User.includes(:posts).take
254
+ user.cacher.posts # => no query will be made even on cache miss.
255
+ ```
256
+
257
+ ## Convenient syntax sugar for caching ActiveRecord
258
+
259
+ ### Caching Associations
260
+ ```rb
261
+ class User < ActiveRecord::Base
262
+ has_one :profile
263
+ cache_at :profile
264
+ end
265
+
266
+ @profile = current_user.cacher.profile
267
+
268
+ # directly get profile without loading user.
269
+ @profile = User.cacher_at(user_id).profile
270
+ ```
271
+
272
+ ### Caching Self
273
+
274
+ Cache self by id:
275
+ ```rb
276
+ class User < ActiveRecord::Base
277
+ cache_self
278
+ end
279
+
280
+ @user = User.cacher.find_by(id: user_id)
281
+
282
+ # peek cache
283
+ User.cacher.peek_by(id: user_id)
284
+
285
+ # clean cache
286
+ User.cacher.clean_by(id: user_id)
287
+ ```
288
+
289
+ Also support caching self by other columns:
290
+ ```rb
291
+ class User < ActiveRecord::Base
292
+ cache_self by: :account
293
+ end
294
+
295
+ @user = User.cacher.find_by(account: 'khiav')
296
+
297
+ # peek cache
298
+ User.cacher.peek_by(account: 'khiav')
299
+
300
+ # clean cache
301
+ User.cacher.clean_by(account: 'khiav')
302
+ ```
303
+
304
+ ### Caching Attributes
305
+
306
+ ```rb
307
+ class Profile < ActiveRecord::Base
308
+ cache_at :point
309
+ end
310
+
311
+ @point = Profile.cacher_at(profile_id).point
312
+ ```
313
+
314
+ ## Options
315
+
316
+ ### :expire_by
317
+
318
+ Monitor on the specific model. Clean the cached objects if targets are changed.
319
+
320
+ - If empty, e.g. `nil` or `''`: Monitoring nothing.
321
+
322
+ - If string, e.g. `User`: Monitoring all attributes of `User`.
323
+
324
+ - If string with keyword `#`, e.g. `User#last_login_in_at`: Monitoring only an specific attribute.
325
+
326
+ - If symbol, e.g. `:posts`: Monitoring on the association. It will monitor all attributes of `Post` and set the `foreign_key'.
327
+
328
+ - The default value depends on the `name`. If `name`:
329
+
330
+ - Is an association, monitoring the association klass
331
+
332
+ - Is an attribute, monitoring current klass and the attribute name
333
+
334
+ - In other cases, monitoring nothing
335
+
336
+ ### :on
337
+
338
+ 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).
339
+
340
+ - if `:create`: Clean the cache only on new record is created, e.g. `Model.create`.
341
+
342
+ - if `:update`: Clean the cache only on the record is updated, e.g. `model.update`.
343
+
344
+ - if `:destroy`: Clean the cache only on the record id destroyed, e.g. `model.destroy`, `model.delete`.
345
+
346
+ - if `array`, e.g. `[:create, :update]`: Clean the cache by any of specified actions.
347
+
348
+ - Default value is `[:create, :update, :destroy]`
349
+
350
+ ### :foreign_key
351
+
352
+ - Is needed only for caching assoication
353
+
354
+ - Does not need to be set if [`expire_by`](#expire_by) is set to monitor association.
355
+
356
+ - 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`).
357
+
358
+ - Has the default value `:id`.
359
+
360
+ - Will be automatically determined if [`expire_by`](#expire_by) is symbol
361
+
362
+ ### :primary_key
363
+
364
+ - Determine which column is going to pass to the query lambda, and to be part of the cache key.<br>
365
+ For example:
366
+
367
+ - **User.cache_at :arbitrary, ->(id){ id }**
368
+
369
+ The cache key will be `active_model_cachers_User_at_arbitrary_#{user.id}`
370
+
371
+ - **User.cache_at :arbitrary, ->(email){ email }, primary_key: :email**
372
+
373
+ The cache key will be `active_model_cachers_User_at_arbitrary_#{user.email}`
374
+
375
+ - Has the default value `:id`.
376
+
377
+ ## Future works
378
+
379
+ - [ ] caching polymorphic associations
380
+ - [ ] non-unique secondary indexes
381
+ - [ ] caching attributes by multiple keys
382
+ - [ ] testing counter cache
383
+ - [ ] testing has_many through
384
+ - [ ] testing has_and_belongs_to_many
385
+
386
+ ## Development
387
+
388
+ After 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.
389
+
390
+ To 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).
391
+
392
+ ## Contributing
393
+
394
+ Bug 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.
395
+
396
+
397
+ ## License
398
+
399
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).