fact_metrics 0.1.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: 77dd1df505a65d11950bc95d193a7812d3814d421c79c02fba3537e289fe3034
4
+ data.tar.gz: 3ec05a41dbcabfca15a2655bba69bc9afea6b0496e4887e83da8b683e99c0338
5
+ SHA512:
6
+ metadata.gz: 47b7f36271813d46ceb7255387c8ad7e861d78457891dabdf2d13ec8233bbb631bacae9d24bbde447b1d6851cc7bf13eb8a2d4318940d6292c4928831b639e8e
7
+ data.tar.gz: b8d7c5096bd94f3b185903f21b285c80430600a590be5a77c47c429e02cbe7434da26b83d76c8f639e7ef6bf913fdc72cb3ac2b34d6453a1a8911fb4b1ce84bd
data/.standard.yml ADDED
@@ -0,0 +1,3 @@
1
+ # For available configuration options, see:
2
+ # https://github.com/standardrb/standard
3
+ ruby_version: 3.0
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2024-12-09
4
+
5
+ - Initial release
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 Scott Maslar
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,57 @@
1
+ # FactMetrics
2
+
3
+ FactMetrics provides a collection of class methods for defining metrics on Fact
4
+ models.
5
+
6
+ ## Installation
7
+
8
+ TODO: Replace `UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG` with your gem name right after releasing it to RubyGems.org. Please do not do it earlier due to security reasons. Alternatively, replace this section with instructions to install your gem from git if you don't plan to release to RubyGems.org.
9
+
10
+ Install the gem and add to the application's Gemfile by executing:
11
+
12
+ ```bash
13
+ bundle add UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG
14
+ ```
15
+
16
+ If bundler is not being used to manage dependencies, install the gem by executing:
17
+
18
+ ```bash
19
+ gem install UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG
20
+ ```
21
+
22
+ ## Usage
23
+
24
+ In your Fact model you can add the following types of metric definitions.
25
+
26
+ ### Counts
27
+
28
+ ```
29
+ count :sales_quantity, all: true
30
+ ```
31
+
32
+ ### Averages
33
+
34
+ ```
35
+ average :regular_unit_price
36
+ ```
37
+
38
+ ### Percentages
39
+
40
+ ```
41
+ percentage :received, field: quantity_received, condition: "> 0"
42
+ percentage :inspected, field: quantity_inspected, condition: "> 0"
43
+ ```
44
+
45
+ ## Development
46
+
47
+ 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.
48
+
49
+ 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).
50
+
51
+ ## Contributing
52
+
53
+ Bug reports and pull requests are welcome on GitHub at https://github.com/PatchMonkeyHQ/fact_metrics.
54
+
55
+ ## License
56
+
57
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "minitest/test_task"
5
+
6
+ Minitest::TestTask.create
7
+
8
+ require "standard/rake"
9
+
10
+ task default: %i[test standard]
@@ -0,0 +1,14 @@
1
+ require "active_support/concern"
2
+
3
+ module FactMetrics::Average
4
+ extend ActiveSupport::Concern
5
+
6
+ class_methods do
7
+ def average(name, uses: nil, **options)
8
+ average_config = FactMetrics::AverageConfig.new(name, uses: uses, **options)
9
+
10
+ scope(average_config.scope_name, -> {select(average_config.sql)} )
11
+ composed_of(*average_config.composed_of_attributes)
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,38 @@
1
+ class FactMetrics::AverageConfig
2
+ attr_reader :name, :uses, :options
3
+
4
+ def initialize(name, uses: nil, **options)
5
+ @name = name
6
+ @uses = uses
7
+ @options = options
8
+ end
9
+
10
+ def scope_name = "#{name}_averages"
11
+ def sql_result_name = "average_#{name}"
12
+ def composed_of_name = "average_#{name}_metric"
13
+
14
+ def composed_of_attributes
15
+ [
16
+ composed_of_name.to_sym,
17
+ class_name: "Metric",
18
+ mapping: {sql_result_name => :value},
19
+ constructor: proc { |value| FactMetrics::Metric.new(value, metric_options) }
20
+ ]
21
+ end
22
+
23
+ def sql
24
+ <<~SQL
25
+ CASE WHEN count(*) != 0 THEN
26
+ AVG(#{field_name})
27
+ END AS #{sql_result_name}
28
+ SQL
29
+ end
30
+
31
+ def field_name
32
+ options[:field] || name.to_s
33
+ end
34
+
35
+ def metric_options
36
+ options.merge({name: composed_of_name})
37
+ end
38
+ end
@@ -0,0 +1,16 @@
1
+
2
+
3
+ module FactMetrics::Count
4
+ extend ActiveSupport::Concern
5
+
6
+ class_methods do
7
+ def count(name, uses: nil, **options)
8
+ count_config = FactMetrics::CountConfig.new(name, **options)
9
+
10
+ scope(count_config.scope_name, -> {select(count_config.sql)} )
11
+ composed_of(*count_config.composed_of_attributes)
12
+
13
+ metric_hash[count_config.scope_name] = [count_config.uses].compact
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,42 @@
1
+ class FactMetrics::CountConfig
2
+ attr_reader :name, :uses, :options
3
+
4
+ def initialize(name, uses: nil, **options)
5
+ @name = name
6
+ @uses = options["uses"] || nil
7
+ @options = options
8
+ end
9
+
10
+ def scope_name = "#{name}_counts"
11
+ def sql_result_name = "#{name}_count"
12
+ def composed_of_name = "#{sql_result_name}_metric"
13
+
14
+ def composed_of_attributes
15
+ [
16
+ composed_of_name.to_sym,
17
+ class_name: "Metric",
18
+ mapping: {sql_result_name => :value},
19
+ constructor: proc { |value| FactMetrics::Metric.new(value, metric_options) }
20
+ ]
21
+ end
22
+
23
+ def sql
24
+ <<~SQL
25
+ COUNT(*) FILTER (WHERE #{condition_sql}) AS #{sql_result_name}
26
+ SQL
27
+ end
28
+
29
+ def condition_sql
30
+ if options[:all] == true
31
+ options[:all].to_s
32
+ elsif options[:equal].present?
33
+ "#{options[:field] || name} = '#{options[:equal]}'"
34
+ elsif options[:condition].present?
35
+ options[:condition].to_s
36
+ end
37
+ end
38
+
39
+ def metric_options
40
+ {name: composed_of_name, precision: 0}.merge(options)
41
+ end
42
+ end
@@ -0,0 +1,35 @@
1
+ class FactMetrics::Metric
2
+ attr_reader :value, :options
3
+
4
+ BLANK = Class.new do
5
+ def method_missing(m, *args, &block)
6
+ if respond_to_missing?(m)
7
+ Metric.new(0, {precision: 0})
8
+ end
9
+ end
10
+
11
+ def respond_to_missing?(m)
12
+ /_metric$/.match?(m)
13
+ end
14
+ end
15
+
16
+ def initialize(value, options)
17
+ @value, @options = value, options
18
+ end
19
+
20
+ def name
21
+ options[:name].humanize
22
+ end
23
+
24
+ def display_value
25
+ (value || 0).round(precision)
26
+ end
27
+
28
+ def precision
29
+ options[:precision] || 1
30
+ end
31
+
32
+ def unit
33
+ options[:unit] || ""
34
+ end
35
+ end
@@ -0,0 +1,14 @@
1
+ module FactMetrics::Percentage
2
+ extend ActiveSupport::Concern
3
+
4
+ class_methods do
5
+ def percentage(name, uses: :itself, **options)
6
+ percentage_config = FactMetrics::PercentageConfig.new(name, uses: uses, **options)
7
+
8
+ scope(percentage_config.scope_name, -> {select(percentage_config.sql)} )
9
+ composed_of(*percentage_config.composed_of_attributes)
10
+
11
+ metric_hash[percentage_config.scope_name] = [percentage_config.uses].compact
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,69 @@
1
+ class FactMetrics::PercentageConfig
2
+ attr_reader :name, :uses, :options
3
+
4
+ def initialize(name, uses: nil, **options)
5
+ @name = name
6
+ @uses = uses
7
+ @options = options
8
+ end
9
+
10
+ def scope_name = "#{name}_percentages"
11
+ def sql_result_name = "#{name}_percentage"
12
+ def composed_of_name = "#{name}_percentage_metric"
13
+
14
+ def composed_of_attributes
15
+ [
16
+ composed_of_name.to_sym,
17
+ class_name: "Metric",
18
+ mapping: {sql_result_name => :value},
19
+ constructor: proc { |value| FactMetrics::Metric.new(value, metric_options) }
20
+ ]
21
+ end
22
+
23
+ def sql
24
+ <<~SQL
25
+ ROUND(
26
+ (
27
+ (COUNT(*) FILTER (WHERE #{condition_sql}))::decimal
28
+ /
29
+ NULLIF(#{denominator_sql}, 0)
30
+ ) * 100,
31
+ 2
32
+ ) AS #{sql_result_name}
33
+ SQL
34
+ end
35
+
36
+ def condition_sql
37
+ if options[:equal]
38
+ "#{field_name} = '#{options[:equal]}'"
39
+ elsif options[:in]
40
+ "#{field_name} IN (#{options[:in].map { |i| "'#{i}'" }.join(",")})"
41
+ elsif options[:condition] && options[:field]
42
+ "#{field_name} #{options[:condition]}"
43
+ elsif options[:condition]
44
+ options[:condition].to_s
45
+ elsif options[:all]
46
+ "true"
47
+ else
48
+ raise "Conditional option ([:equal, :in, :condition, :all]) required to determine percentage."
49
+ end
50
+ end
51
+
52
+ def denominator_sql
53
+ if options[:denominator] == :all
54
+ "COUNT(*)"
55
+ elsif options[:denominator]
56
+ "MAX(#{options[:denominator]})"
57
+ else
58
+ "SUM(CASE WHEN #{field_name} IS NOT NULL THEN 1 END)"
59
+ end
60
+ end
61
+
62
+ def field_name
63
+ options[:field] || name
64
+ end
65
+
66
+ def metric_options
67
+ {name: composed_of_name, unit: "%"}.merge(options)
68
+ end
69
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FactMetrics
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "fact_metrics/version"
4
+ require_relative "fact_metrics/average"
5
+ require_relative "fact_metrics/count"
6
+ require_relative "fact_metrics/percentage"
7
+ require_relative "fact_metrics/average_config"
8
+ require_relative "fact_metrics/count_config"
9
+ require_relative "fact_metrics/percentage_config"
10
+ require_relative "fact_metrics/metric"
11
+ require "active_support/concern"
12
+
13
+ module FactMetrics
14
+ class Error < StandardError; end
15
+ extend ActiveSupport::Concern
16
+
17
+ included do
18
+ class_attribute :metric_hash, default: {}
19
+ end
20
+
21
+ include Average
22
+ include Count
23
+ include Percentage
24
+
25
+ class_methods do
26
+ def all_metrics
27
+ load_metrics(*metric_hash.keys)
28
+ end
29
+
30
+ def load_metrics(*metrics)
31
+ metrics = metrics.map(&:to_s)
32
+ metric_prerequisites = metrics.flat_map { |metric| metric_hash.fetch(metric) }.compact.uniq
33
+ metric_query = (metric_prerequisites + metrics).inject(self) { |model_klass, metric_method| model_klass.send(metric_method) }
34
+
35
+ # ActiveRecord short-circuits "impossible" predicates, returning an empty array.
36
+ # In aggregation queries, however, results can still be meaningful without matching rows.
37
+ # To ensure the query executes, replace the conditional with one that cannot be short-circuited.
38
+ if metric_query.where_clause.contradiction?
39
+ metric_query.where_clause = ActiveRecord::Relation::WhereClause.empty
40
+ metric_query.where!("1=0")
41
+ end
42
+
43
+ metric_query
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,4 @@
1
+ module FactMetrics
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,76 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: fact_metrics
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Scott Maslar
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2024-12-31 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activesupport
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '6.0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '6.0'
27
+ description: Kimball Fact tables have typical aggregations, this gem makes implementing
28
+ them straightforward.
29
+ email:
30
+ - scott@patchmonkey.io
31
+ executables: []
32
+ extensions: []
33
+ extra_rdoc_files: []
34
+ files:
35
+ - ".standard.yml"
36
+ - CHANGELOG.md
37
+ - LICENSE.txt
38
+ - README.md
39
+ - Rakefile
40
+ - lib/fact_metrics.rb
41
+ - lib/fact_metrics/average.rb
42
+ - lib/fact_metrics/average_config.rb
43
+ - lib/fact_metrics/count.rb
44
+ - lib/fact_metrics/count_config.rb
45
+ - lib/fact_metrics/metric.rb
46
+ - lib/fact_metrics/percentage.rb
47
+ - lib/fact_metrics/percentage_config.rb
48
+ - lib/fact_metrics/version.rb
49
+ - sig/fact_metrics.rbs
50
+ homepage: https://github.com/PatchMonkeyHQ/fact_metrics
51
+ licenses:
52
+ - MIT
53
+ metadata:
54
+ homepage_uri: https://github.com/PatchMonkeyHQ/fact_metrics
55
+ source_code_uri: https://github.com/PatchMonkeyHQ/fact_metric
56
+ changelog_uri: https://github.com/PatchMonkeyHQ/fact_metrics/blob/main/CHANGELOG.md
57
+ post_install_message:
58
+ rdoc_options: []
59
+ require_paths:
60
+ - lib
61
+ required_ruby_version: !ruby/object:Gem::Requirement
62
+ requirements:
63
+ - - ">="
64
+ - !ruby/object:Gem::Version
65
+ version: 3.0.0
66
+ required_rubygems_version: !ruby/object:Gem::Requirement
67
+ requirements:
68
+ - - ">="
69
+ - !ruby/object:Gem::Version
70
+ version: '0'
71
+ requirements: []
72
+ rubygems_version: 3.4.19
73
+ signing_key:
74
+ specification_version: 4
75
+ summary: Adds support for aggregations on Kimball style Fact models.
76
+ test_files: []