fancy_count 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: e2ba88cb0b55ed68589f1351b496862c524ac6c8da25f8848b92ba23296e73ff
4
+ data.tar.gz: d9c96c1f7e783d2e361bd8038f1b0f268ed2a6f6cb1cab40642b987710c03ef0
5
+ SHA512:
6
+ metadata.gz: cfcd3ffc28610abdd1c3e63188f18f70ef485959a3f3877e584df2dbe61642be9940bb603fde6eba71a09427dcd7bfe7c6c0cf2f7c21c950b6ca08b18f70bc60
7
+ data.tar.gz: 755a6f3797337dcda7e2a64f2ee59df3ccb059bdb3b5689369d9a592d0de4a9aae6f484af452ce950467c6018c8e7cd44b466fdce73ef8bd5754a9ae2b1b88b2
data/.gitignore ADDED
@@ -0,0 +1,12 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
12
+ *.DS_Store
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2021-04-26
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at TODO: Write your email address. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ rails_version = ENV["RAILS_VERSION"]
6
+ gem "activerecord", rails_version
7
+
8
+ sqlite_version = ENV["SQLITE_VERSION"]
9
+
10
+ if sqlite_version.present?
11
+ gem "sqlite3", sqlite_version
12
+ end
13
+
14
+ gemspec
data/Gemfile.lock ADDED
@@ -0,0 +1,96 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ fancy_count (0.1.0)
5
+ activerecord (>= 4.2, < 7)
6
+ activesupport (>= 4.2, < 7)
7
+ discard (>= 1.0)
8
+
9
+ GEM
10
+ remote: https://rubygems.org/
11
+ specs:
12
+ activemodel (6.1.3.1)
13
+ activesupport (= 6.1.3.1)
14
+ activerecord (6.1.3.1)
15
+ activemodel (= 6.1.3.1)
16
+ activesupport (= 6.1.3.1)
17
+ activesupport (6.1.3.1)
18
+ concurrent-ruby (~> 1.0, >= 1.0.2)
19
+ i18n (>= 1.6, < 2)
20
+ minitest (>= 5.1)
21
+ tzinfo (~> 2.0)
22
+ zeitwerk (~> 2.3)
23
+ ast (2.4.2)
24
+ concurrent-ruby (1.1.8)
25
+ database_cleaner-active_record (2.0.0)
26
+ activerecord (>= 5.a)
27
+ database_cleaner-core (~> 2.0.0)
28
+ database_cleaner-core (2.0.1)
29
+ diff-lcs (1.4.4)
30
+ discard (1.2.0)
31
+ activerecord (>= 4.2, < 7)
32
+ i18n (1.8.10)
33
+ concurrent-ruby (~> 1.0)
34
+ minitest (5.14.4)
35
+ parallel (1.20.1)
36
+ parser (3.0.1.1)
37
+ ast (~> 2.4.1)
38
+ rainbow (3.0.0)
39
+ rake (13.0.3)
40
+ regexp_parser (2.1.1)
41
+ rexml (3.2.5)
42
+ rspec (3.10.0)
43
+ rspec-core (~> 3.10.0)
44
+ rspec-expectations (~> 3.10.0)
45
+ rspec-mocks (~> 3.10.0)
46
+ rspec-core (3.10.1)
47
+ rspec-support (~> 3.10.0)
48
+ rspec-expectations (3.10.1)
49
+ diff-lcs (>= 1.2.0, < 2.0)
50
+ rspec-support (~> 3.10.0)
51
+ rspec-mocks (3.10.2)
52
+ diff-lcs (>= 1.2.0, < 2.0)
53
+ rspec-support (~> 3.10.0)
54
+ rspec-support (3.10.2)
55
+ rubocop (1.14.0)
56
+ parallel (~> 1.10)
57
+ parser (>= 3.0.0.0)
58
+ rainbow (>= 2.2.2, < 4.0)
59
+ regexp_parser (>= 1.8, < 3.0)
60
+ rexml
61
+ rubocop-ast (>= 1.5.0, < 2.0)
62
+ ruby-progressbar (~> 1.7)
63
+ unicode-display_width (>= 1.4.0, < 3.0)
64
+ rubocop-ast (1.7.0)
65
+ parser (>= 3.0.1.1)
66
+ rubocop-performance (1.11.2)
67
+ rubocop (>= 1.7.0, < 2.0)
68
+ rubocop-ast (>= 0.4.0)
69
+ ruby-progressbar (1.11.0)
70
+ sqlite3 (1.4.2)
71
+ standard (1.1.1)
72
+ rubocop (= 1.14.0)
73
+ rubocop-performance (= 1.11.2)
74
+ tzinfo (2.0.4)
75
+ concurrent-ruby (~> 1.0)
76
+ unicode-display_width (2.0.0)
77
+ with_model (2.1.5)
78
+ activerecord (>= 5.2)
79
+ zeitwerk (2.4.2)
80
+
81
+ PLATFORMS
82
+ ruby
83
+
84
+ DEPENDENCIES
85
+ activerecord
86
+ bundler
87
+ database_cleaner-active_record (~> 2.0)
88
+ fancy_count!
89
+ rake (>= 10.0)
90
+ rspec (>= 3.5.0)
91
+ sqlite3
92
+ standard
93
+ with_model (~> 2.0)
94
+
95
+ BUNDLED WITH
96
+ 2.1.4
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2021 TODO: Write your name
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 ADDED
@@ -0,0 +1,43 @@
1
+ # FancyCount
2
+
3
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/fancy_count`. To experiment with that code, run `bin/console` for an interactive prompt.
4
+
5
+ TODO: Delete this and the text above, and describe your gem
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'fancy_count'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle install
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install fancy_count
22
+
23
+ ## Usage
24
+
25
+ TODO: Write usage instructions here
26
+
27
+ ## Development
28
+
29
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
30
+
31
+ 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 the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
32
+
33
+ ## Contributing
34
+
35
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/fancy_count. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/fancy_count/blob/master/CODE_OF_CONDUCT.md).
36
+
37
+ ## License
38
+
39
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
40
+
41
+ ## Code of Conduct
42
+
43
+ Everyone interacting in the FancyCount project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/fancy_count/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ task default: :spec
data/bin/console ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "fancy_count"
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require "irb"
15
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,42 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/fancy_count/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "fancy_count"
7
+ spec.version = FancyCount::VERSION
8
+ spec.authors = ["CompanyCam Engineering"]
9
+ spec.email = ["engineering@companycam.com"]
10
+
11
+ spec.summary = "Yet Another Counter Library"
12
+ spec.description = "A small library to count things. Use Redis, Memory, or bring your own storage!"
13
+ spec.homepage = "https://companycam.com"
14
+ spec.license = "MIT"
15
+ spec.required_ruby_version = Gem::Requirement.new(">= 2.4.0")
16
+
17
+ spec.metadata["allowed_push_host"] = "https://rubygems.org"
18
+
19
+ spec.metadata["homepage_uri"] = spec.homepage
20
+ spec.metadata["source_code_uri"] = "https://github.com/CompanyCam/fancy-count"
21
+ spec.metadata["changelog_uri"] = "https://github.com/CompanyCam/fancy-count/blob/main/CHANGELOG.md"
22
+
23
+ # Specify which files should be added to the gem when it is released.
24
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
25
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
26
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features)/}) }
27
+ end
28
+ spec.bindir = "exe"
29
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
30
+ spec.require_paths = ["lib"]
31
+
32
+ spec.add_dependency "activerecord", ">= 4.2", "< 7"
33
+ spec.add_dependency "activesupport", ">= 4.2", "< 7"
34
+ spec.add_dependency "discard", ">= 1.0"
35
+ spec.add_development_dependency "bundler"
36
+ spec.add_development_dependency "standard"
37
+ spec.add_development_dependency "rake", ">= 10.0"
38
+ spec.add_development_dependency "rspec", ">= 3.5.0"
39
+ spec.add_development_dependency "database_cleaner-active_record", "~> 2.0"
40
+ spec.add_development_dependency "with_model", "~> 2.0"
41
+ spec.add_development_dependency "sqlite3"
42
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "fancy_count/version"
4
+ require_relative "fancy_count/adapter"
5
+ require_relative "fancy_count/redis_adapter"
6
+ require_relative "fancy_count/test_adapter"
7
+ require_relative "fancy_count/configuration"
8
+ require_relative "fancy_count/counter"
9
+ require_relative "fancy_count/has_countable"
10
+ require_relative "fancy_count/counter_cacheable"
11
+
12
+ module FancyCount
13
+ class Error < StandardError; end
14
+
15
+ class MissingAdapterError < Error; end
16
+
17
+ class UnknownCounterError < StandardError; end
18
+
19
+ class MissingLogicError < StandardError; end
20
+
21
+ def self.configure
22
+ yield config if block_given?
23
+ end
24
+
25
+ def self.config
26
+ @config ||= Configuration.new
27
+ end
28
+ end
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FancyCount
4
+ class Adapter
5
+ def initialize(name)
6
+ @name = name
7
+ end
8
+
9
+ def increment
10
+ counter.increment
11
+ end
12
+
13
+ def decrement
14
+ counter.decrement
15
+ end
16
+
17
+ def change(value)
18
+ counter.value = value
19
+ end
20
+
21
+ def reset
22
+ counter.value = 0
23
+ end
24
+
25
+ def value
26
+ counter.value
27
+ end
28
+
29
+ def delete
30
+ counter.delete
31
+ end
32
+
33
+ private
34
+
35
+ def counter
36
+ raise "Not yet implemented"
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support/configurable"
4
+
5
+ module FancyCount
6
+ class Configuration
7
+ include ActiveSupport::Configurable
8
+
9
+ config_accessor :adapter
10
+
11
+ ADAPTER_CLASSES = {
12
+ redis: FancyCount::RedisAdapter,
13
+ test: FancyCount::TestAdapter
14
+ }
15
+
16
+ def self.adapter=(value)
17
+ if ADAPTER_CLASSES.key?(value.to_sym)
18
+ super(value)
19
+ else
20
+ raise_missing_adapter_error(value)
21
+ end
22
+ end
23
+
24
+ def adapter_class
25
+ @adapter_class ||= ADAPTER_CLASSES[adapter.to_sym]
26
+ end
27
+
28
+ private
29
+
30
+ def raise_missing_adapter_error(adapter_name)
31
+ message = "Missing adapter for #{adapter_name}, valid adapters are #{ADAPTER_CLASSES.keys.join("")}"
32
+ raise FancyCount::MissingAdapterError.new(message)
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FancyCount
4
+ class Counter
5
+ def initialize(name, config = nil)
6
+ @name = name
7
+ @config = config || ::FancyCount.config
8
+ end
9
+
10
+ def increment
11
+ adapter.increment
12
+ end
13
+
14
+ def decrement
15
+ adapter.decrement
16
+ end
17
+
18
+ def change(value)
19
+ adapter.change(value)
20
+ end
21
+
22
+ def reset
23
+ adapter.reset
24
+ end
25
+
26
+ def value
27
+ adapter.value
28
+ end
29
+
30
+ def delete
31
+ adapter.delete
32
+ end
33
+
34
+ private
35
+
36
+ def adapter
37
+ @adapter ||= @config.adapter_class.new(@name)
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,102 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FancyCount
4
+ module CounterCacheable
5
+ extend ActiveSupport::Concern
6
+
7
+ # This is the "magic module" can should be included to automatically update
8
+ # "fancy" counter caches defined on a corresponding model.
9
+ #
10
+ # Example:
11
+ #
12
+ # class Person < ActiveRecord::Base
13
+ # include FancyCount::Countable
14
+ #
15
+ # fancy_counter :children
16
+ # end
17
+ #
18
+ # class Child < ActiveRecord::Base
19
+ # include FancyCount::CounterCacheable
20
+ #
21
+ # belongs_to :parent, class_name: "Person"
22
+ #
23
+ # fancy_counter_cache :children, on: :parent
24
+ # end
25
+ #
26
+ # This will take care of incrementing or decrementing the children count on the Person
27
+ # model, whenever a child record is created or destroyed.
28
+
29
+ class_methods do
30
+ def fancy_counter_caches
31
+ @fancy_counter_caches ||= []
32
+ end
33
+
34
+ def fancy_counter_cache(name, options = {})
35
+ counter_method_name = "fancy_#{name.to_s.singularize}_counter"
36
+ association_name = options[:on]
37
+
38
+ fancy_counter_caches << {name: name, counter_name: counter_method_name, association_name: association_name}
39
+
40
+ after_create do
41
+ fancy_association = public_send(association_name)
42
+ fancy_association.public_send(counter_method_name).increment
43
+ end
44
+
45
+ if respond_to?(:after_discard)
46
+ after_discard do
47
+ fancy_association = public_send(association_name)
48
+ fancy_association.public_send(counter_method_name).decrement
49
+ end
50
+
51
+ after_undiscard do
52
+ fancy_association = public_send(association_name)
53
+ fancy_association.public_send(counter_method_name).increment
54
+ end
55
+ else
56
+ after_destroy do
57
+ fancy_association = public_send(association_name)
58
+ fancy_association.public_send(counter_method_name).decrement
59
+ end
60
+ end
61
+ end
62
+
63
+ def fancy_counter_cache_reconcile(name, scope: nil)
64
+ data = fancy_counter_caches.detect { |entry| entry[:name] == name }
65
+ raise "Unknown counter #{name}" if data.blank?
66
+
67
+ scope ||= all
68
+ association_data = reflect_on_association(data[:association_name])
69
+
70
+ if association_data.polymorphic?
71
+ scope = scope.distinct("#{data[:association_name]}_type, #{data[:association_name]}_id")
72
+ else
73
+ foreign_key = association_data.foreign_key
74
+ scope = scope.distinct(foreign_key)
75
+ end
76
+
77
+ scope.find_each(batch_size: 100) do |record|
78
+ record.fancy_counter_cache_reconcile(name)
79
+ end
80
+ end
81
+ end
82
+
83
+ def fancy_counter_cache_reconcile(name)
84
+ data = self.class.fancy_counter_caches.detect { |entry| entry[:name] == name }
85
+ raise "Unknown counter #{name}" if data.blank?
86
+
87
+ association = public_send(data[:association_name])
88
+ new_count = fancy_association_count(association, name)
89
+ association.public_send(data[:counter_name]).change(new_count)
90
+ end
91
+
92
+ def fancy_association_count(association, counter_name)
93
+ scope = association.public_send(counter_name)
94
+
95
+ if association.respond_to?(:kept)
96
+ scope = scope.kept
97
+ end
98
+
99
+ scope.count
100
+ end
101
+ end
102
+ end
@@ -0,0 +1,123 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FancyCount
4
+ module HasCountable
5
+ extend ActiveSupport::Concern
6
+
7
+ # This is the module we mix into ActiveRecord models. It is responsible for
8
+ # two things:
9
+ #
10
+ # * Providing an interface to the counter
11
+ # * Deleting the counter after the record is destroyed
12
+ #
13
+ # Important: This do not automagically provide a working counter cache. It simple
14
+ # exposes an interface that you can use to manage one.
15
+ #
16
+ # Example:
17
+ #
18
+ # class Person < ActiveRecord::Base
19
+ # include FancyCount::Countable
20
+ #
21
+ # fancy_counter :phone_numbers
22
+ # end
23
+ #
24
+ # bob = Person.new
25
+ # bob.fancy_phone_number_count => 0
26
+ # bob.fancy_phone_number_counter => <Fancy::Counter>
27
+ #
28
+ # Counters can be incremented:
29
+ # bob.fancy_phone_number_counter.increment
30
+ # bob.fancy_phone_number_count => 1
31
+ #
32
+ # Counters can be decremented:
33
+ # bob.fancy_phone_number_counter.decrement
34
+ # bob.fancy_phone_number_count => 0
35
+ #
36
+ # Counters can explicitly have their values set:
37
+ # bob.fancy_phone_number_counter.change(3)
38
+ # bob.fancy_phone_number_count => 3
39
+ #
40
+ # Counters can easily be reset to zero:
41
+ # bob.fancy_phone_number_counter.reset
42
+ # bob.fancy_phone_number_count => 0
43
+
44
+ class_methods do
45
+ def fancy_counters
46
+ @fancy_counters ||= []
47
+ end
48
+
49
+ # DANGER: This is a VERY naive method. It is not written to be hyper performant.
50
+ # Do not run this on Images, Locations, Videos, or other HUGE tables!!!!
51
+ def fancy_counters_reconcile(name, scope: nil)
52
+ scope ||= all
53
+ scope.find_each(batch_size: 100) { |record| record.fancy_counters_reconcile(name) }
54
+ end
55
+
56
+ def fancy_counter(name, options = {})
57
+ counter_method_name = "fancy_#{name.to_s.singularize}_counter"
58
+ count_method_name = "fancy_#{name.to_s.singularize}_count"
59
+ lazily_recalculate_counter = false
60
+
61
+ fancy_counters << {name: name, counter_name: counter_method_name, reconcile_logic: options[:reconcile_logic]}
62
+
63
+ if options[:reconcile_on_missing] && !options[:reconcile_logic]
64
+ raise ArgumentError.new("reconcile is required")
65
+ end
66
+
67
+ if options[:reconcile_on_missing] && options[:reconcile_logic]
68
+ lazily_recalculate_counter = true
69
+ end
70
+
71
+ define_method counter_method_name do
72
+ counter_key = "#{id}_#{self.class.name.underscore}_#{counter_method_name}"
73
+ current_value = fancy_counter_value(counter_key)
74
+ counter = ::FancyCount::Counter.new(counter_key)
75
+
76
+ if lazily_recalculate_counter && current_value.nil?
77
+ starting_value = send(options[:reconcile_logic])
78
+ counter.change(starting_value)
79
+ end
80
+
81
+ counter
82
+ end
83
+
84
+ define_method count_method_name do
85
+ public_send(counter_method_name).value
86
+ end
87
+
88
+ if respond_to?(:after_discard)
89
+ after_discard do
90
+ # Remove the key/value from Redis/adapter
91
+ public_send(counter_method_name).delete
92
+ end
93
+ else
94
+ after_destroy do
95
+ # Remove the key/value from Redis/adapter
96
+ public_send(counter_method_name).delete
97
+ end
98
+ end
99
+ end
100
+ end
101
+
102
+ def fancy_counter_value(counter_key)
103
+ case FancyCount.config.adapter
104
+ when :redis
105
+ Redis::Objects.redis.get(counter_key)
106
+ when :test
107
+ FancyCount::TestAdapter.counts[counter_key]
108
+ else
109
+ raise "Unknown adapter: #{FancyCount.config.adapter}"
110
+ end
111
+ end
112
+
113
+ def fancy_counters_reconcile(name)
114
+ count_method_name = "fancy_#{name.to_s.singularize}_count"
115
+ data = self.class.fancy_counters.detect { |entry| entry[:name] == name.to_sym }
116
+ raise UnknownCounterError.new("#{count_method_name} doesn't exist") if data.nil?
117
+ raise MissingLogicError.new("#{count_method_name} doesn't have ':reconcile'") unless data.has_key?(:reconcile_logic)
118
+
119
+ new_count = send(data[:reconcile_logic])
120
+ public_send(data[:counter_name]).change(new_count)
121
+ end
122
+ end
123
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FancyCount
4
+ class RedisAdapter < Adapter
5
+ def counter
6
+ @counter ||= Redis::Counter.new(@name)
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,49 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FancyCount
4
+ class TestAdapter < Adapter
5
+ @@counts = {}
6
+
7
+ def self.reset
8
+ self.counts = {}
9
+ end
10
+
11
+ def self.counts
12
+ @@counts
13
+ end
14
+
15
+ def self.counts=(value)
16
+ @@counts = value
17
+ end
18
+
19
+ def initialize(name)
20
+ super(name)
21
+ self.class.counts ||= {}
22
+ self.class.counts[name] ||= 0
23
+ end
24
+
25
+ def increment
26
+ self.class.counts[@name] += 1
27
+ end
28
+
29
+ def decrement
30
+ self.class.counts[@name] -= 1
31
+ end
32
+
33
+ def change(value)
34
+ self.class.counts[@name] = value
35
+ end
36
+
37
+ def reset
38
+ self.class.counts[@name] = 0
39
+ end
40
+
41
+ def value
42
+ self.class.counts[@name]
43
+ end
44
+
45
+ def delete
46
+ self.class.counts.delete(@name)
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FancyCount
4
+ VERSION = "1.0.0"
5
+ end
metadata ADDED
@@ -0,0 +1,221 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: fancy_count
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - CompanyCam Engineering
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2021-06-09 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activerecord
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '4.2'
20
+ - - "<"
21
+ - !ruby/object:Gem::Version
22
+ version: '7'
23
+ type: :runtime
24
+ prerelease: false
25
+ version_requirements: !ruby/object:Gem::Requirement
26
+ requirements:
27
+ - - ">="
28
+ - !ruby/object:Gem::Version
29
+ version: '4.2'
30
+ - - "<"
31
+ - !ruby/object:Gem::Version
32
+ version: '7'
33
+ - !ruby/object:Gem::Dependency
34
+ name: activesupport
35
+ requirement: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - ">="
38
+ - !ruby/object:Gem::Version
39
+ version: '4.2'
40
+ - - "<"
41
+ - !ruby/object:Gem::Version
42
+ version: '7'
43
+ type: :runtime
44
+ prerelease: false
45
+ version_requirements: !ruby/object:Gem::Requirement
46
+ requirements:
47
+ - - ">="
48
+ - !ruby/object:Gem::Version
49
+ version: '4.2'
50
+ - - "<"
51
+ - !ruby/object:Gem::Version
52
+ version: '7'
53
+ - !ruby/object:Gem::Dependency
54
+ name: discard
55
+ requirement: !ruby/object:Gem::Requirement
56
+ requirements:
57
+ - - ">="
58
+ - !ruby/object:Gem::Version
59
+ version: '1.0'
60
+ type: :runtime
61
+ prerelease: false
62
+ version_requirements: !ruby/object:Gem::Requirement
63
+ requirements:
64
+ - - ">="
65
+ - !ruby/object:Gem::Version
66
+ version: '1.0'
67
+ - !ruby/object:Gem::Dependency
68
+ name: bundler
69
+ requirement: !ruby/object:Gem::Requirement
70
+ requirements:
71
+ - - ">="
72
+ - !ruby/object:Gem::Version
73
+ version: '0'
74
+ type: :development
75
+ prerelease: false
76
+ version_requirements: !ruby/object:Gem::Requirement
77
+ requirements:
78
+ - - ">="
79
+ - !ruby/object:Gem::Version
80
+ version: '0'
81
+ - !ruby/object:Gem::Dependency
82
+ name: standard
83
+ requirement: !ruby/object:Gem::Requirement
84
+ requirements:
85
+ - - ">="
86
+ - !ruby/object:Gem::Version
87
+ version: '0'
88
+ type: :development
89
+ prerelease: false
90
+ version_requirements: !ruby/object:Gem::Requirement
91
+ requirements:
92
+ - - ">="
93
+ - !ruby/object:Gem::Version
94
+ version: '0'
95
+ - !ruby/object:Gem::Dependency
96
+ name: rake
97
+ requirement: !ruby/object:Gem::Requirement
98
+ requirements:
99
+ - - ">="
100
+ - !ruby/object:Gem::Version
101
+ version: '10.0'
102
+ type: :development
103
+ prerelease: false
104
+ version_requirements: !ruby/object:Gem::Requirement
105
+ requirements:
106
+ - - ">="
107
+ - !ruby/object:Gem::Version
108
+ version: '10.0'
109
+ - !ruby/object:Gem::Dependency
110
+ name: rspec
111
+ requirement: !ruby/object:Gem::Requirement
112
+ requirements:
113
+ - - ">="
114
+ - !ruby/object:Gem::Version
115
+ version: 3.5.0
116
+ type: :development
117
+ prerelease: false
118
+ version_requirements: !ruby/object:Gem::Requirement
119
+ requirements:
120
+ - - ">="
121
+ - !ruby/object:Gem::Version
122
+ version: 3.5.0
123
+ - !ruby/object:Gem::Dependency
124
+ name: database_cleaner-active_record
125
+ requirement: !ruby/object:Gem::Requirement
126
+ requirements:
127
+ - - "~>"
128
+ - !ruby/object:Gem::Version
129
+ version: '2.0'
130
+ type: :development
131
+ prerelease: false
132
+ version_requirements: !ruby/object:Gem::Requirement
133
+ requirements:
134
+ - - "~>"
135
+ - !ruby/object:Gem::Version
136
+ version: '2.0'
137
+ - !ruby/object:Gem::Dependency
138
+ name: with_model
139
+ requirement: !ruby/object:Gem::Requirement
140
+ requirements:
141
+ - - "~>"
142
+ - !ruby/object:Gem::Version
143
+ version: '2.0'
144
+ type: :development
145
+ prerelease: false
146
+ version_requirements: !ruby/object:Gem::Requirement
147
+ requirements:
148
+ - - "~>"
149
+ - !ruby/object:Gem::Version
150
+ version: '2.0'
151
+ - !ruby/object:Gem::Dependency
152
+ name: sqlite3
153
+ requirement: !ruby/object:Gem::Requirement
154
+ requirements:
155
+ - - ">="
156
+ - !ruby/object:Gem::Version
157
+ version: '0'
158
+ type: :development
159
+ prerelease: false
160
+ version_requirements: !ruby/object:Gem::Requirement
161
+ requirements:
162
+ - - ">="
163
+ - !ruby/object:Gem::Version
164
+ version: '0'
165
+ description: A small library to count things. Use Redis, Memory, or bring your own
166
+ storage!
167
+ email:
168
+ - engineering@companycam.com
169
+ executables: []
170
+ extensions: []
171
+ extra_rdoc_files: []
172
+ files:
173
+ - ".gitignore"
174
+ - ".rspec"
175
+ - CHANGELOG.md
176
+ - CODE_OF_CONDUCT.md
177
+ - Gemfile
178
+ - Gemfile.lock
179
+ - LICENSE.txt
180
+ - README.md
181
+ - Rakefile
182
+ - bin/console
183
+ - bin/setup
184
+ - fancy_count.gemspec
185
+ - lib/fancy_count.rb
186
+ - lib/fancy_count/adapter.rb
187
+ - lib/fancy_count/configuration.rb
188
+ - lib/fancy_count/counter.rb
189
+ - lib/fancy_count/counter_cacheable.rb
190
+ - lib/fancy_count/has_countable.rb
191
+ - lib/fancy_count/redis_adapter.rb
192
+ - lib/fancy_count/test_adapter.rb
193
+ - lib/fancy_count/version.rb
194
+ homepage: https://companycam.com
195
+ licenses:
196
+ - MIT
197
+ metadata:
198
+ allowed_push_host: https://rubygems.org
199
+ homepage_uri: https://companycam.com
200
+ source_code_uri: https://github.com/CompanyCam/fancy-count
201
+ changelog_uri: https://github.com/CompanyCam/fancy-count/blob/main/CHANGELOG.md
202
+ post_install_message:
203
+ rdoc_options: []
204
+ require_paths:
205
+ - lib
206
+ required_ruby_version: !ruby/object:Gem::Requirement
207
+ requirements:
208
+ - - ">="
209
+ - !ruby/object:Gem::Version
210
+ version: 2.4.0
211
+ required_rubygems_version: !ruby/object:Gem::Requirement
212
+ requirements:
213
+ - - ">="
214
+ - !ruby/object:Gem::Version
215
+ version: '0'
216
+ requirements: []
217
+ rubygems_version: 3.1.2
218
+ signing_key:
219
+ specification_version: 4
220
+ summary: Yet Another Counter Library
221
+ test_files: []