n1_loader 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 8e2a77c7fdcb24c0ad611468803c952e120c43b2c54be109828380d01723dd3f
4
+ data.tar.gz: 37dfae873e6cba9e5539b4609d324ff3fc5489d5be305eec1bbac5389089379c
5
+ SHA512:
6
+ metadata.gz: 8fe48829416810c0fac586dbe4b5002e4de2906d5ed1d99813d094c77db29d1a941cf742d078463632a0802fecfea55cc091e469b7510d2d566a4f2acdb1413f
7
+ data.tar.gz: 71038ccc2403d0baae719ebbd9a00ed7351e1370c255bf5bd3a5d826d4d6824323c53bd317d7193bc92a175b1786abb2b27a64b45e34d97c6427baaee3c58844
@@ -0,0 +1,104 @@
1
+ version: 2.1
2
+
3
+ executors:
4
+ ruby:
5
+ description: The official CircleCI Ruby Docker image
6
+ parameters:
7
+ tag:
8
+ description: The circleci/ruby Docker image version tag
9
+ type: string
10
+ default: latest
11
+ docker:
12
+ - image: circleci/ruby:<< parameters.tag >>
13
+ environment:
14
+ - BUNDLE_JOBS: 4
15
+ - BUNDLE_RETRY: 3
16
+ working_directory: ~/n1_loader
17
+
18
+ jobs:
19
+ checkout:
20
+ executor: ruby
21
+ steps:
22
+ - checkout
23
+ - persist_to_workspace:
24
+ root: ~/n1_loader
25
+ paths:
26
+ - .
27
+
28
+ build:
29
+ parameters:
30
+ ruby-version:
31
+ type: string
32
+ gemfile:
33
+ type: string
34
+ executor:
35
+ name: ruby
36
+ tag: << parameters.ruby-version >>
37
+ steps:
38
+ - attach_workspace:
39
+ at: ~/n1_loader
40
+ - run:
41
+ name: Use << parameters.gemfile >> as the Gemfile
42
+ command: bundle config --global gemfile << parameters.gemfile >>
43
+ - run:
44
+ name: Install the gems specified by the Gemfile
45
+ command: bundle install
46
+ - run:
47
+ name: Run RSpec
48
+ command: |
49
+ bundle exec rspec --profile 10 \
50
+ --format RspecJunitFormatter \
51
+ --out test_results/rspec.xml \
52
+ --format progress \
53
+ $(circleci tests glob "spec/**/*_spec.rb" | circleci tests split --split-by=timings)
54
+ - store_test_results:
55
+ path: test_results
56
+
57
+ rubocop:
58
+ executor:
59
+ name: ruby
60
+ tag: "2.5"
61
+ steps:
62
+ - attach_workspace:
63
+ at: ~/n1_loader
64
+ - run:
65
+ name: Install the gems specified by the Gemfile
66
+ command: bundle install
67
+ - run:
68
+ name: Lint Ruby code with RuboCop
69
+ command: bundle exec rubocop --parallel
70
+
71
+ workflows:
72
+ version: 2
73
+ default: &default
74
+ jobs:
75
+ - checkout
76
+ - build:
77
+ requires:
78
+ - checkout
79
+ matrix:
80
+ parameters:
81
+ ruby-version: [
82
+ "2.5",
83
+ "2.6",
84
+ "2.7",
85
+ "3.0",
86
+ "latest"
87
+ ]
88
+ gemfile: [
89
+ "gemfiles/ar_6_latest.gemfile"
90
+ ]
91
+ name: << matrix.gemfile >>-build-ruby-<< matrix.ruby-version >>
92
+ - rubocop:
93
+ requires:
94
+ - checkout
95
+
96
+ nightly:
97
+ triggers:
98
+ - schedule:
99
+ cron: "0 0 * * *"
100
+ filters:
101
+ branches:
102
+ only:
103
+ - master
104
+ <<: *default
data/.gitignore ADDED
@@ -0,0 +1,11 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+ /.idea
10
+ .rspec_status
11
+ Gemfile.lock
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,17 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.5
3
+
4
+ Style/StringLiterals:
5
+ Enabled: true
6
+ EnforcedStyle: double_quotes
7
+
8
+ Style/StringLiteralsInInterpolation:
9
+ Enabled: true
10
+ EnforcedStyle: double_quotes
11
+
12
+ Layout/LineLength:
13
+ Max: 120
14
+
15
+ Metrics/BlockLength:
16
+ Exclude:
17
+ - spec/**/*
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2021-12-16
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,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in n1_loader.gemspec
6
+ gemspec
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,158 @@
1
+ # N1Loader
2
+
3
+ [![CircleCI][1]][2]
4
+ [![Gem Version][3]][4]
5
+
6
+ Are you tired of fixing [N+1 issues][7]? Does it feel unnatural to you to fix it case by case in places where you need the data?
7
+ We have a solution for you! [N1Loader][8] is designed to solve the issue for good!
8
+
9
+ It has many benefits:
10
+ - it loads data lazily (even when you initialized preloading)
11
+ - it supports shared loaders between multiple classes
12
+ - it has an integration with [ActiveRecord][5] which makes it brilliant ([example](#activerecord))
13
+ - it has an integration with [ArLazyPreload][6] which makes it excellent ([example](#arlazypreload))
14
+
15
+
16
+ ## Installation
17
+
18
+ Add this line to your application's Gemfile:
19
+
20
+ ```ruby
21
+ gem 'n1_loader'
22
+ ```
23
+
24
+ You can add integration with [ActiveRecord][5] by:
25
+ ```ruby
26
+ require 'n1_loader/active_record'
27
+ ```
28
+
29
+ You can add the integration with [ActiveRecord][5] and [ArLazyPreload][6] by:
30
+ ```ruby
31
+ require 'n1_loader/ar_lazy_preload'
32
+ ```
33
+
34
+ ## Usage
35
+
36
+ ```ruby
37
+ class Example
38
+ include N1Loader::Loadable
39
+
40
+ # with inline loader
41
+ n1_loader :anything do |elements|
42
+ # Has to return a hash that has keys as element from elements
43
+ elements.group_by(&:itself)
44
+ end
45
+
46
+ # with custom loader
47
+ n1_loader :something, MyLoader
48
+ end
49
+
50
+ # Custom loader that can be shared with many classes
51
+ class MyLoader < N1Loader::Loader
52
+ # Has to return a hash that has keys as element from elements
53
+ def perform(elements)
54
+ elements.group_by(&:itself)
55
+ end
56
+ end
57
+
58
+ # For single object
59
+ ex = Example.new
60
+ ex.anything
61
+
62
+ # For multiple objects without N+1
63
+ objects = [Example.new, Example.new]
64
+ N1Loader::Preloader.new(objects).preload(:anything)
65
+ objects.map(&:anything)
66
+ ```
67
+
68
+ ### [ActiveRecord][5]
69
+
70
+ ```ruby
71
+ class User < ActiveRecord::Base
72
+ include N1Loader::Loadable
73
+
74
+ n1_loader :orders_count do |users|
75
+ hash = Order.where(user: users).group(:user_id).count
76
+
77
+ # hash has to have keys as initial elements
78
+ hash.transform_keys! { |key| users.find { |user| user.id == key } }
79
+ end
80
+ end
81
+
82
+ # For single user
83
+ user = User.first
84
+ user.orders_count
85
+
86
+ # For many users without N+1
87
+ User.limit(5).includes(:orders_count).map(&:orders_count)
88
+
89
+ # or with explicit preloader
90
+ users = User.limit(5).to_a
91
+ N1Loader::Preloader.new(users).preload(:orders_count)
92
+
93
+ # No N+1 here
94
+ users.map(&:orders_count)
95
+ ```
96
+
97
+ ### [ArLazyPreload][6]
98
+
99
+ ```ruby
100
+ class User < ActiveRecord::Base
101
+ include N1Loader::Loadable
102
+
103
+ n1_loader :orders_count do |users|
104
+ hash = Order.where(user: users).group(:user_id).count
105
+
106
+ # hash has to have keys as initial elements
107
+ hash.transform_keys! { |key| users.find { |user| user.id == key } }
108
+ end
109
+ end
110
+
111
+ # For single user
112
+ user = User.first
113
+ user.orders_count
114
+
115
+ # For many users without N+1
116
+ User.lazy_preload(:orders_count).all.map(&:orders_count)
117
+ # or
118
+ User.preload_associations_lazily.all.map(&:orders_count)
119
+ # or
120
+ ArLazyPreload.config.auto_preload = true
121
+ User.all.map(:orders_count)
122
+ ```
123
+
124
+ ## Development
125
+
126
+ 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.
127
+
128
+ 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).
129
+
130
+ ## Contributing
131
+
132
+ Bug reports and pull requests are welcome on GitHub at https://github.com/djezzzl/n1_loader.
133
+ This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](CODE_OF_CONDUCT.md).
134
+
135
+ ## License
136
+
137
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
138
+
139
+ ## Code of Conduct
140
+
141
+ Everyone interacting in the N1Loader project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](CODE_OF_CONDUCT.md).
142
+
143
+ ## Changelog
144
+
145
+ *N1Loader*'s changelog is available [here](CHANGELOG.md).
146
+
147
+ ## Copyright
148
+
149
+ Copyright (c) Evgeniy Demin. See [LICENSE.txt](LICENSE.txt) for further details.
150
+
151
+ [1]: https://circleci.com/gh/djezzzl/n1_loader/tree/master.svg?style=shield
152
+ [2]: https://circleci.com/gh/djezzzl/n1_loader/tree/master
153
+ [3]: https://badge.fury.io/rb/n1_loader.svg
154
+ [4]: https://badge.fury.io/rb/n1_loader
155
+ [5]: https://github.com/rails/rails/tree/main/activerecord
156
+ [6]: https://github.com/DmitryTsepelev/ar_lazy_preload
157
+ [7]: https://stackoverflow.com/questions/97197/what-is-the-n1-selects-problem-in-orm-object-relational-mapping
158
+ [8]: https://github.com/djezzzl/n1_loader
data/Rakefile ADDED
@@ -0,0 +1,12 @@
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
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
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 "n1_loader"
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,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ gem "activerecord", "~> 6"
6
+
7
+ gemspec path: "../"
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ module N1Loader
4
+ module ActiveRecord
5
+ module Associations
6
+ module Preloader # :nodoc:
7
+ N1LoaderReflection = Struct.new(:key, :loader) do
8
+ def options
9
+ {}
10
+ end
11
+ end
12
+
13
+ def preloaders_for_reflection(reflection, records, scope)
14
+ return super unless reflection.is_a?(N1LoaderReflection)
15
+
16
+ N1Loader::Preloader.new(records).preload(reflection.key)
17
+ end
18
+
19
+ def grouped_records(association, records, polymorphic_parent)
20
+ n1_load_records, records = records.partition { |record| record.class.n1_loader_defined?(association) }
21
+
22
+ hash = n1_load_records.group_by do |record|
23
+ N1LoaderReflection.new(association, record.class.n1_loader(association))
24
+ end
25
+
26
+ hash.merge(super)
27
+ end
28
+ end
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_record"
4
+
5
+ require_relative "active_record/associations_preloader"
6
+
7
+ ActiveSupport.on_load(:active_record) do
8
+ ActiveRecord::Associations::Preloader.prepend(N1Loader::ActiveRecord::Associations::Preloader)
9
+ end
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ module N1Loader
4
+ module ArLazyPreload
5
+ # Context builder for N1Loader
6
+ class AssociatedContextBuilder < ::ArLazyPreload::AssociatedContextBuilder
7
+ def perform
8
+ ::ArLazyPreload::Context.register(
9
+ records: parent_context.records.flat_map(&association_name),
10
+ association_tree: child_association_tree,
11
+ auto_preload: parent_context.auto_preload?
12
+ )
13
+ end
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ module N1Loader
4
+ module ArLazyPreload
5
+ # Context adapter for N1Loader
6
+ class ContextAdapter
7
+ attr_reader :context
8
+
9
+ delegate :records, :auto_preload?, to: :context
10
+
11
+ def initialize(context)
12
+ @context = context
13
+ end
14
+
15
+ def try_preload_lazily(association_name)
16
+ return unless context&.send(:association_needs_preload?, association_name)
17
+
18
+ perform_preloading(association_name)
19
+ end
20
+
21
+ def perform_preloading(association_name)
22
+ N1Loader::Preloader.new(records).preload(association_name)
23
+
24
+ AssociatedContextBuilder.prepare(
25
+ parent_context: self,
26
+ association_name: association_name
27
+ )
28
+ end
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ module N1Loader
4
+ module ArLazyPreload
5
+ module Loadable
6
+ module ClassMethods # :nodoc:
7
+ def n1_load(name, loader = nil, &block)
8
+ name, loader_name, loader_variable_name = super
9
+
10
+ define_method(loader_name) do
11
+ loader = instance_variable_get(loader_variable_name)
12
+
13
+ return loader if loader
14
+ if respond_to?(:lazy_preload_context) && ContextAdapter.new(lazy_preload_context).try_preload_lazily(name)
15
+ return instance_variable_get(loader_variable_name)
16
+ end
17
+
18
+ instance_variable_set(loader_variable_name, self.class.send(loader_name).new([self]))
19
+ end
20
+ end
21
+ end
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "active_record"
4
+
5
+ require "rails"
6
+ require "ar_lazy_preload"
7
+
8
+ require_relative "ar_lazy_preload/loadable"
9
+ require_relative "ar_lazy_preload/context_adapter"
10
+ require_relative "ar_lazy_preload/associated_context_builder"
11
+
12
+ N1Loader::Loadable::ClassMethods.prepend(N1Loader::ArLazyPreload::Loadable::ClassMethods)
@@ -0,0 +1,79 @@
1
+ # frozen_string_literal: true
2
+
3
+ module N1Loader
4
+ # The module to be included to the class to define associated loaders.
5
+ #
6
+ # class Example
7
+ # include N1Loader::Loadable
8
+ #
9
+ # # with inline loader
10
+ # n1_loader :something do |elements|
11
+ # elements.each_with_object({}) do |element, hash|
12
+ # hash[element] = element.calculate_something
13
+ # end
14
+ # end
15
+ #
16
+ # # with custom loader
17
+ # n1_loader :something, MyLoader
18
+ # end
19
+ #
20
+ # # custom loader
21
+ # class MyLoader < N1Loader::Loader
22
+ # def perform(elements)
23
+ # elements.each_with_object({}) do |element, hash|
24
+ # hash[element] = element.calculate_something
25
+ # end
26
+ # end
27
+ # end
28
+ module Loadable
29
+ def n1_loader(name)
30
+ send("#{name}_loader")
31
+ end
32
+
33
+ def n1_loader_set(name, loader)
34
+ send("#{name}_loader=", loader)
35
+ end
36
+
37
+ def self.included(base)
38
+ base.extend(ClassMethods)
39
+ end
40
+
41
+ module ClassMethods # :nodoc:
42
+ def n1_loader(name)
43
+ send("#{name}_loader")
44
+ end
45
+
46
+ def n1_loader_defined?(name)
47
+ respond_to?("#{name}_loader")
48
+ end
49
+
50
+ def n1_load(name, loader = nil, &block) # rubocop:disable Metrics/MethodLength
51
+ loader ||= Class.new(N1Loader::Loader) do
52
+ define_method(:perform, &block)
53
+ end
54
+
55
+ loader_name = "#{name}_loader"
56
+ loader_variable_name = "@#{loader_name}"
57
+
58
+ define_singleton_method(loader_name) do
59
+ loader
60
+ end
61
+
62
+ define_method("#{loader_name}=") do |loader_instance|
63
+ instance_variable_set(loader_variable_name, loader_instance)
64
+ end
65
+
66
+ define_method(loader_name) do
67
+ instance_variable_get(loader_variable_name) ||
68
+ instance_variable_set(loader_variable_name, self.class.send(loader_name).new([self]))
69
+ end
70
+
71
+ define_method(name) do
72
+ send(loader_name).for(self)
73
+ end
74
+
75
+ [name, loader_name, loader_variable_name]
76
+ end
77
+ end
78
+ end
79
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ module N1Loader
4
+ # Loader that performs the loading.
5
+ #
6
+ # Subclasses must define +perform+ method that accepts single argument
7
+ # and returns hash where key is the element and value is what we want to load.
8
+ class Loader
9
+ def initialize(elements)
10
+ @elements = elements
11
+ end
12
+
13
+ def perform(_elements)
14
+ raise NotImplemented, "Subclasses have to implement the method"
15
+ end
16
+
17
+ def loaded
18
+ @loaded ||= perform(elements)
19
+ end
20
+
21
+ def preloaded_records
22
+ @preloaded_records ||= loaded.values
23
+ end
24
+
25
+ def for(element)
26
+ raise NotLoaded, "The data was not preloaded for the given element" unless elements.include?(element)
27
+
28
+ loaded.compare_by_identity[element]
29
+ end
30
+
31
+ private
32
+
33
+ attr_reader :elements
34
+ end
35
+ end
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ module N1Loader
4
+ # Preloader that lazily preloads data to every element.
5
+ #
6
+ # It supports multiple keys.
7
+ #
8
+ # It supports elements that have different loaders under the same key.
9
+ # It will properly preload data to each of the element of the similar group.
10
+ class Preloader
11
+ attr_reader :elements
12
+
13
+ def initialize(elements)
14
+ @elements = elements
15
+ end
16
+
17
+ def preload(*keys)
18
+ keys.flatten(1).flat_map do |key|
19
+ elements
20
+ .group_by { |element| element.class.n1_loader(key) }
21
+ .map do |loader_class, grouped_elements|
22
+ loader = loader_class.new(grouped_elements)
23
+ grouped_elements.each { |grouped_element| grouped_element.n1_loader_set(key, loader) }
24
+ loader
25
+ end
26
+ end
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module N1Loader
4
+ VERSION = "0.1.0"
5
+ end
data/lib/n1_loader.rb ADDED
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "n1_loader/version"
4
+
5
+ require_relative "n1_loader/loader"
6
+ require_relative "n1_loader/loadable"
7
+ require_relative "n1_loader/preloader"
8
+
9
+ module N1Loader # :nodoc:
10
+ class Error < StandardError; end
11
+ class NotImplemented < Error; end
12
+ class NotLoaded < Error; end
13
+ end
data/n1_loader.gemspec ADDED
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/n1_loader/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "n1_loader"
7
+ spec.version = N1Loader::VERSION
8
+ spec.authors = ["Evgeniy Demin"]
9
+ spec.email = ["lawliet.djez@gmail.com"]
10
+
11
+ spec.summary = "N+1 loader to solve the problem for good."
12
+ spec.homepage = "https://github.com/djezzzl/n1_loader"
13
+ spec.license = "MIT"
14
+ spec.required_ruby_version = ">= 2.5.0"
15
+
16
+ spec.metadata["homepage_uri"] = spec.homepage
17
+ spec.metadata["source_code_uri"] = "https://github.com/djezzzl/database_consistency"
18
+ spec.metadata["changelog_uri"] = "https://github.com/djezzzl/database_consistency/master/CHANGELOG.md"
19
+
20
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
21
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features)/}) }
22
+ end
23
+ spec.require_paths = ["lib"]
24
+
25
+ spec.add_development_dependency "activerecord", "~> 6.0"
26
+ spec.add_development_dependency "ar_lazy_preload", "~> 0.7"
27
+ spec.add_development_dependency "db-query-matchers", "~> 0.10"
28
+ spec.add_development_dependency "rails", "~> 6.0"
29
+ spec.add_development_dependency "rspec", "~> 3.0"
30
+ spec.add_development_dependency "rspec_junit_formatter", "~> 0.4"
31
+ spec.add_development_dependency "rubocop", "~> 1.7"
32
+ spec.add_development_dependency "sqlite3", "~> 1.3"
33
+ end
metadata ADDED
@@ -0,0 +1,183 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: n1_loader
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Evgeniy Demin
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2021-12-18 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: '6.0'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '6.0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: ar_lazy_preload
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '0.7'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '0.7'
41
+ - !ruby/object:Gem::Dependency
42
+ name: db-query-matchers
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '0.10'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '0.10'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rails
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '6.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '6.0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: rspec
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '3.0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '3.0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: rspec_junit_formatter
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - "~>"
88
+ - !ruby/object:Gem::Version
89
+ version: '0.4'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - "~>"
95
+ - !ruby/object:Gem::Version
96
+ version: '0.4'
97
+ - !ruby/object:Gem::Dependency
98
+ name: rubocop
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - "~>"
102
+ - !ruby/object:Gem::Version
103
+ version: '1.7'
104
+ type: :development
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - "~>"
109
+ - !ruby/object:Gem::Version
110
+ version: '1.7'
111
+ - !ruby/object:Gem::Dependency
112
+ name: sqlite3
113
+ requirement: !ruby/object:Gem::Requirement
114
+ requirements:
115
+ - - "~>"
116
+ - !ruby/object:Gem::Version
117
+ version: '1.3'
118
+ type: :development
119
+ prerelease: false
120
+ version_requirements: !ruby/object:Gem::Requirement
121
+ requirements:
122
+ - - "~>"
123
+ - !ruby/object:Gem::Version
124
+ version: '1.3'
125
+ description:
126
+ email:
127
+ - lawliet.djez@gmail.com
128
+ executables: []
129
+ extensions: []
130
+ extra_rdoc_files: []
131
+ files:
132
+ - ".circleci/config.yml"
133
+ - ".gitignore"
134
+ - ".rspec"
135
+ - ".rubocop.yml"
136
+ - CHANGELOG.md
137
+ - CODE_OF_CONDUCT.md
138
+ - Gemfile
139
+ - LICENSE.txt
140
+ - README.md
141
+ - Rakefile
142
+ - bin/console
143
+ - bin/setup
144
+ - gemfiles/ar_6_latest.gemfile
145
+ - lib/n1_loader.rb
146
+ - lib/n1_loader/active_record.rb
147
+ - lib/n1_loader/active_record/associations_preloader.rb
148
+ - lib/n1_loader/ar_lazy_preload.rb
149
+ - lib/n1_loader/ar_lazy_preload/associated_context_builder.rb
150
+ - lib/n1_loader/ar_lazy_preload/context_adapter.rb
151
+ - lib/n1_loader/ar_lazy_preload/loadable.rb
152
+ - lib/n1_loader/loadable.rb
153
+ - lib/n1_loader/loader.rb
154
+ - lib/n1_loader/preloader.rb
155
+ - lib/n1_loader/version.rb
156
+ - n1_loader.gemspec
157
+ homepage: https://github.com/djezzzl/n1_loader
158
+ licenses:
159
+ - MIT
160
+ metadata:
161
+ homepage_uri: https://github.com/djezzzl/n1_loader
162
+ source_code_uri: https://github.com/djezzzl/database_consistency
163
+ changelog_uri: https://github.com/djezzzl/database_consistency/master/CHANGELOG.md
164
+ post_install_message:
165
+ rdoc_options: []
166
+ require_paths:
167
+ - lib
168
+ required_ruby_version: !ruby/object:Gem::Requirement
169
+ requirements:
170
+ - - ">="
171
+ - !ruby/object:Gem::Version
172
+ version: 2.5.0
173
+ required_rubygems_version: !ruby/object:Gem::Requirement
174
+ requirements:
175
+ - - ">="
176
+ - !ruby/object:Gem::Version
177
+ version: '0'
178
+ requirements: []
179
+ rubygems_version: 3.2.22
180
+ signing_key:
181
+ specification_version: 4
182
+ summary: N+1 loader to solve the problem for good.
183
+ test_files: []