grape-entity-preloader 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: 3d32cc4a359717abe3519c7f8bee48d9e35029d1348057a7fa35b043594dd1b5
4
+ data.tar.gz: 9ef42ce05db679a5cf7830aeaae698b1557452957648e668ced0ced0cd1e4a3a
5
+ SHA512:
6
+ metadata.gz: e9101088f6433f7372ad46b061c34341553259a91a3f903ec1d2dde1112bd2e2d944aec61fcb4ba1ac5ae5828719b3d9eb9dfda88134351e739982e8a8e03149
7
+ data.tar.gz: 6d46c749603a41caff0bec514091adc6b630d521c2d0b84aa62f879f76058b4d81185a493f1684eb5f54548290d702462a946cd1c3617af420fd469f16bb023a
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] - 2025-10-12 UTC
4
+
5
+ - Initial release
@@ -0,0 +1,132 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, caste, color, religion, or sexual
10
+ identity and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the overall
26
+ community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or advances of
31
+ any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email address,
35
+ without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official email address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ [INSERT CONTACT METHOD].
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series of
86
+ actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or permanent
93
+ ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within the
113
+ community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.1, available at
119
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
+
121
+ Community Impact Guidelines were inspired by
122
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123
+
124
+ For answers to common questions about this code of conduct, see the FAQ at
125
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126
+ [https://www.contributor-covenant.org/translations][translations].
127
+
128
+ [homepage]: https://www.contributor-covenant.org
129
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
+ [Mozilla CoC]: https://github.com/mozilla/diversity
131
+ [FAQ]: https://www.contributor-covenant.org/faq
132
+ [translations]: https://www.contributor-covenant.org/translations
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 OuYangJinTing
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,188 @@
1
+ # Grape::Entity::Preloader
2
+
3
+ Grape::Entity::Preloader allows preload associations and callbacks for avoiding N+1 operations in Grape::Entity.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ bundle add grape-entity-preloader
9
+ ```
10
+
11
+ If bundler is not being used to manage dependencies, install the gem by executing:
12
+
13
+ ```bash
14
+ gem install grape-entity-preloader
15
+ ```
16
+
17
+ ## Usage
18
+
19
+ ### Activation
20
+
21
+ #### Global Activation
22
+
23
+ You can enable the preloader globally. This is useful in environments where you want preloading to be the default behavior.
24
+
25
+ ```ruby
26
+ # config/initializers/grape_entity_preloader.rb
27
+ Grape::Entity::Preloader.enabled!
28
+ ```
29
+
30
+ #### Local Activation and Deactivation
31
+
32
+ You can control preloading for specific `represent` calls.
33
+
34
+ ##### 1. Using options
35
+
36
+ Pass `grape_entity_preloader: :enabled` or `grape_entity_preloader: :disabled` to the options hash. This overrides the global setting.
37
+
38
+ ```ruby
39
+ # Locally enable
40
+ MyEntity.represent(users, grape_entity_preloader: :enabled)
41
+
42
+ # Locally disable
43
+ MyEntity.represent(users, grape_entity_preloader: :disabled)
44
+ ```
45
+
46
+ ##### 2. Using a block
47
+
48
+ For a specific block of code, you can use `with_enable` or `with_disable`. This is useful in contexts like API endpoints or middlewares.
49
+
50
+ ```ruby
51
+ Grape::Entity::Preloader.with_enable do
52
+ # Preloading is enabled for all represent calls inside this block
53
+ MyAPI::Entities::User.represent(User.all)
54
+ end
55
+
56
+ Grape::Entity::Preloader.with_disable do
57
+ # Preloading is disabled for all represent calls inside this block
58
+ MyAPI::Entities::User.represent(User.all)
59
+ end
60
+ ```
61
+
62
+ ### `preload_association`
63
+
64
+ Use `preload_association` to preload ActiveRecord associations. This helps to avoid N+1 queries when an exposure represents an association.
65
+
66
+ ```ruby
67
+ class UserEntity < Grape::Entity
68
+ expose :id
69
+ expose :name
70
+ # This will preload the `books` association for all users being represented.
71
+ expose :books, using: BookEntity, preload_association: :books
72
+ end
73
+
74
+ # In your API
75
+ users = User.limit(10)
76
+ # When UserEntity represents users, it will execute two queries:
77
+ # 1. SELECT * FROM users LIMIT 10
78
+ # 2. SELECT * FROM books WHERE books.user_id IN (...)
79
+ UserEntity.represent(users)
80
+ ```
81
+
82
+ For nested preloading:
83
+
84
+ ```ruby
85
+ class BookEntity < Grape::Entity
86
+ expose :id
87
+ expose :title
88
+ # This will preload tags for each book
89
+ expose :tags, using: TagEntity, preload_association: :tags
90
+ end
91
+
92
+ class UserEntity < Grape::Entity
93
+ expose :id
94
+ expose :name
95
+ expose :books, using: BookEntity, preload_association: :books
96
+ end
97
+
98
+ # It will generate 3 queries instead of 1 + 10 (for books) + N (for tags)
99
+ UserEntity.represent(User.limit(10))
100
+ ```
101
+
102
+ ### `preload_callback`
103
+
104
+ For more complex scenarios that `preload_association` doesn't cover (e.g., loading data from other services, custom caching logic), you can use `preload_callback`.
105
+
106
+ It must be a `Proc` that accepts two arguments:
107
+ 1. `objects`: An array of the parent objects being represented.
108
+ 2. `options`: The `Grape::Entity::Options` object for the current representation context.
109
+
110
+ **The `Proc` should return an array of objects that will be used for the nested entity representation. These returned objects will then be passed to the preloader for that nested entity, allowing for further nested preloading.**
111
+
112
+ ```ruby
113
+ class UserStatsEntity < Grape::Entity
114
+ expose :likes
115
+ expose :followers
116
+ end
117
+
118
+ class UserEntity < Grape::Entity
119
+ expose :id
120
+ expose :name
121
+
122
+ expose :stats, using: UserStatsEntity, preload_callback: ->(users, _options) do
123
+ # `users` is an array of User objects.
124
+ # Here you can fetch stats for all users in one batch.
125
+ user_ids = users.map(&:id)
126
+ stats_data = StatsService.batch_get_by_user_ids(user_ids) # returns a hash { user_id => stats_object }
127
+
128
+ # The preloader needs to associate the loaded data back to the original objects.
129
+ # A common pattern is to attach the data to a new attribute on the object.
130
+ users.each { |user| user.instance_variable_set(:@stats, stats_data[user.id]) }
131
+
132
+ # The block must return the objects that will be presented by the nested entity.
133
+ # In this case, it's the stats objects we just loaded.
134
+ users.map { |user| user.instance_variable_get(:@stats) }
135
+ end
136
+ end
137
+
138
+ # In the entity, you need to define how to access the preloaded data.
139
+ class UserEntity < Grape::Entity
140
+ # ...
141
+ expose :stats, using: UserStatsEntity, preload_callback: ... do |user, _options|
142
+ user.instance_variable_get(:@stats)
143
+ end
144
+ end
145
+ ```
146
+
147
+ ### `preload_condition`
148
+
149
+ Use `preload_condition` to conditionally enable or disable preloading for an exposure. It must be a `Proc` that accepts one argument: `options`, which is the `Grape::Entity::Options` object.
150
+
151
+ If the `Proc` returns a falsy value, preloading for that exposure will be skipped.
152
+
153
+ ```ruby
154
+ class UserEntity < Grape::Entity
155
+ expose :id
156
+ expose :name
157
+
158
+ # The :audit_log association will only be preloaded if `include_audit_log` is true in the options.
159
+ expose :audit_log,
160
+ using: AuditLogEntity,
161
+ preload_association: :audit_log,
162
+ preload_condition: ->(options) { options[:include_audit_log] }
163
+ end
164
+
165
+ # Preloading for :audit_log is skipped
166
+ UserEntity.represent(user)
167
+
168
+ # Preloading for :audit_log is executed
169
+ UserEntity.represent(user, include_audit_log: true)
170
+ ```
171
+
172
+ ## Development
173
+
174
+ 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.
175
+
176
+ 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).
177
+
178
+ ## Contributing
179
+
180
+ Bug reports and pull requests are welcome on GitHub at https://github.com/OuYangJinTing/grape-entity-preloader. 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/OuYangJinTing/grape-entity-preloader/blob/master/CODE_OF_CONDUCT.md).
181
+
182
+ ## License
183
+
184
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
185
+
186
+ ## Code of Conduct
187
+
188
+ Everyone interacting in the Grape::Entity::Preloader project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/OuYangJinTing/grape-entity-preloader/blob/master/CODE_OF_CONDUCT.md).
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]
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Grape
4
+ class Entity
5
+ class Preloader
6
+ module Entity # rubocop:disable Style/Documentation
7
+ extend ActiveSupport::Concern
8
+
9
+ module ClassMethods # rubocop:disable Style/Documentation
10
+ def represent(objects, options = {})
11
+ options = Grape::Entity::Options.new(options) unless options.is_a?(Grape::Entity::Options)
12
+
13
+ options[:grape_entity_preloader] ||= Preloader.enabled? ? :enabled : :disabled
14
+ Preloader.new(root_exposures, objects, options).call if options[:grape_entity_preloader] == :enabled
15
+ options[:grape_entity_preloader] = :finished
16
+
17
+ super(objects, options)
18
+ end
19
+ end
20
+ end
21
+ end
22
+ end
23
+ end
24
+
25
+ Grape::Entity.prepend(Grape::Entity::Preloader::Entity)
26
+ silence_warnings do
27
+ Grape::Entity::OPTIONS = (Grape::Entity::OPTIONS + %i[preload_association preload_callback preload_condition]).freeze
28
+ end
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Grape
4
+ class Entity
5
+ class Preloader
6
+ module Exposure
7
+ module Base # rubocop:disable Style/Documentation
8
+ extend ActiveSupport::Concern
9
+
10
+ attr_reader :preload_association, :preload_callback, :preload_condition
11
+
12
+ def initialize(_attribute, options, _conditions)
13
+ @preload_association = options[:preload_association]
14
+ @preload_callback = options[:preload_callback]
15
+ @preload_condition = options[:preload_condition]
16
+ validate_preload_options
17
+
18
+ super
19
+ end
20
+
21
+ private
22
+
23
+ def validate_preload_options # rubocop:disable Metrics/AbcSize,Metrics/CyclomaticComplexity,Metrics/PerceivedComplexity,Metrics/MethodLength
24
+ if preload_association && !preload_association.is_a?(Symbol)
25
+ raise ArgumentError, 'The :preload_association option must be a Symbol.'
26
+ end
27
+
28
+ if preload_callback && (!preload_callback.is_a?(Proc) || preload_callback.arity != 2)
29
+ raise ArgumentError, 'The :preload_callback option must be a Proc with 2 arguments.'
30
+ end
31
+
32
+ if preload_condition && (!preload_condition.is_a?(Proc) || preload_condition.arity != 1)
33
+ raise ArgumentError, 'The :preload_condition option must be a Proc with 1 argument.'
34
+ end
35
+
36
+ return unless preload_association && preload_callback
37
+
38
+ raise ArgumentError, 'The :preload_association and :preload_callback options cannot be used together.'
39
+ end
40
+ end
41
+ end
42
+ end
43
+ end
44
+ end
45
+
46
+ Grape::Entity::Exposure::Base.prepend(Grape::Entity::Preloader::Exposure::Base)
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Grape
4
+ class Entity
5
+ class Preloader
6
+ module Options # rubocop:disable Style/Documentation
7
+ extend ActiveSupport::Concern
8
+
9
+ included do
10
+ def_delegators :opts_hash, :delete, :[]=
11
+ end
12
+ end
13
+ end
14
+ end
15
+ end
16
+
17
+ Grape::Entity::Options.include(Grape::Entity::Preloader::Options)
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Grape
4
+ class Entity
5
+ class Preloader
6
+ VERSION = '0.1.0'
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,166 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'grape-entity'
4
+ require_relative 'preloader/version'
5
+ require_relative 'preloader/entity'
6
+ require_relative 'preloader/options'
7
+ require_relative 'preloader/exposure/base'
8
+
9
+ module Grape
10
+ class Entity
11
+ class Preloader # rubocop:disable Style/Documentation,Metrics/ClassLength
12
+ attr_reader :exposures, :objects, :options, :associations, :callbacks, :nested_association_chain
13
+
14
+ singleton_class.attr_accessor :enabled
15
+ self.enabled = false
16
+
17
+ def self.enabled!
18
+ self.enabled = true
19
+ end
20
+
21
+ def self.enabled?
22
+ if ActiveSupport::IsolatedExecutionState.key?(:grape_entity_preloader)
23
+ ActiveSupport::IsolatedExecutionState[:grape_entity_preloader]
24
+ else
25
+ enabled
26
+ end
27
+ end
28
+
29
+ def self.with_enable
30
+ return yield if enabled?
31
+
32
+ old_value = ActiveSupport::IsolatedExecutionState[:grape_entity_preloader]
33
+ ActiveSupport::IsolatedExecutionState[:grape_entity_preloader] = true
34
+
35
+ yield
36
+
37
+ if old_value.nil?
38
+ ActiveSupport::IsolatedExecutionState.delete(:grape_entity_preloader)
39
+ else
40
+ ActiveSupport::IsolatedExecutionState[:grape_entity_preloader] = old_value
41
+ end
42
+ end
43
+
44
+ def self.disabled!
45
+ self.enabled = false
46
+ end
47
+
48
+ def self.disabled?
49
+ !enabled?
50
+ end
51
+
52
+ def self.with_disable
53
+ return yield if disabled?
54
+
55
+ old_value = ActiveSupport::IsolatedExecutionState[:grape_entity_preloader]
56
+ ActiveSupport::IsolatedExecutionState[:grape_entity_preloader] = false
57
+
58
+ yield
59
+
60
+ if old_value.nil?
61
+ ActiveSupport::IsolatedExecutionState.delete(:grape_entity_preloader)
62
+ else
63
+ ActiveSupport::IsolatedExecutionState[:grape_entity_preloader] = old_value
64
+ end
65
+ end
66
+
67
+ def self.activerecord_gte_7_0?
68
+ unless defined?(ActiveRecord) && ActiveRecord.respond_to?(:version) && ActiveRecord.version >= Gem::Version.new('7.0')
69
+ warn 'ActiveRecord 7.0 or later is required for preload association'
70
+ return false
71
+ end
72
+
73
+ true
74
+ end
75
+
76
+ def initialize(exposures, objects, options)
77
+ @exposures = exposures
78
+ @objects = Array.wrap(objects)
79
+ @options = options
80
+
81
+ @associations = {}
82
+ @callbacks = Hash.new { |hash, key| hash[key] = [] }
83
+ @nested_association_chain = []
84
+ end
85
+
86
+ def call
87
+ return if objects.empty?
88
+
89
+ extract_preload_options(exposures, options, associations)
90
+ execute_preload_associations
91
+ execute_preload_callbacks
92
+ end
93
+
94
+ private
95
+
96
+ def execute_preload_associations
97
+ return unless Preloader.activerecord_gte_7_0?
98
+ return if associations.empty?
99
+
100
+ # TODO: Change ActiveRecord async query
101
+ ActiveRecord::Associations::Preloader.new(records: objects, associations: associations).call
102
+ end
103
+
104
+ def execute_preload_callbacks # rubocop:disable Metrics/AbcSize,Metrics/MethodLength,Metrics/CyclomaticComplexity
105
+ callbacks.each do |association_chain, exposures_with_options|
106
+ association_objects = association_chain.inject(objects) do |items, association|
107
+ items.filter_map(&association).flatten(1)
108
+ end
109
+ next if association_objects.empty?
110
+
111
+ exposures_with_options.each do |exposure, options|
112
+ callback_objects = exposure.preload_callback.call(association_objects, options)
113
+ # Dynamic keys are difficult to handle and less used, skipped directly
114
+ next if !exposure.is_a?(Grape::Entity::Exposure::RepresentExposure) || exposure_with_dynamic_key?(exposure)
115
+
116
+ Preloader.new(
117
+ exposure.using_class.root_exposures,
118
+ callback_objects,
119
+ nesting_options(exposure, options)
120
+ ).call
121
+ end
122
+ end
123
+ end
124
+
125
+ def extract_preload_options(exposures, options, associations) # rubocop:disable Metrics/AbcSize,Metrics/CyclomaticComplexity,Metrics/PerceivedComplexity,Metrics/MethodLength
126
+ exposures.each do |exposure|
127
+ next unless exposure.should_return_key?(options)
128
+ next if exposure.preload_condition && !exposure.preload_condition.call(options)
129
+
130
+ if exposure.preload_callback
131
+ callbacks[nested_association_chain.dup] << [exposure, options]
132
+ elsif exposure.preload_association && Preloader.activerecord_gte_7_0?
133
+ associations[exposure.preload_association] ||= {}
134
+ end
135
+
136
+ # Dynamic keys are difficult to handle and less used, skipped directly
137
+ next if exposure_with_dynamic_key?(exposure)
138
+
139
+ if exposure.is_a?(Grape::Entity::Exposure::NestingExposure)
140
+ extract_preload_options(
141
+ exposure.nested_exposures,
142
+ nesting_options(exposure, options),
143
+ associations
144
+ )
145
+ elsif exposure.is_a?(Grape::Entity::Exposure::RepresentExposure) && associations[exposure.preload_association]
146
+ nested_association_chain.push(exposure.preload_association)
147
+ extract_preload_options(
148
+ exposure.using_class.root_exposures,
149
+ nesting_options(exposure, options),
150
+ associations[exposure.preload_association]
151
+ )
152
+ nested_association_chain.pop
153
+ end
154
+ end
155
+ end
156
+
157
+ def nesting_options(exposure, options)
158
+ options.for_nesting(exposure.instance_variable_get(:@key))
159
+ end
160
+
161
+ def exposure_with_dynamic_key?(exposure)
162
+ exposure.instance_variable_get(:@key).respond_to?(:call)
163
+ end
164
+ end
165
+ end
166
+ end
@@ -0,0 +1,8 @@
1
+ module Grape
2
+ module Entity
3
+ module Preloader
4
+ VERSION: String
5
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
6
+ end
7
+ end
8
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ RSpec.describe Grape::Entity::Preloader do
4
+ it 'has a version number' do
5
+ expect(Grape::Entity::Preloader::VERSION).not_to be_nil
6
+ end
7
+ end
@@ -0,0 +1,187 @@
1
+ # frozen_string_literal: true
2
+
3
+ RSpec.describe 'N+1 operation' do # rubocop:disable RSpec/DescribeClass
4
+ before(:context) do
5
+ Grape::Entity::Preloader.enabled!
6
+
7
+ user1 = User.create(name: 'User1')
8
+ user2 = User.create(name: 'User2')
9
+
10
+ book1 = Book.create(name: 'Book1', author: user1)
11
+ book2 = Book.create(name: 'Book2', author: user2)
12
+
13
+ Tag.create(name: 'UserTag1', target: user1)
14
+ Tag.create(name: 'UserTag2', target: user1)
15
+
16
+ Tag.create(name: 'BookTag1', target: book1)
17
+ Tag.create(name: 'BookTag2', target: book2)
18
+ end
19
+
20
+ describe 'preloader enabled & disabled' do
21
+ let!(:books) { Book.all.load }
22
+
23
+ before do
24
+ Grape::Entity::Preloader.enabled = false # restore default value
25
+ end
26
+
27
+ describe 'enabled' do
28
+ it '.enabled!' do
29
+ Grape::Entity::Preloader.enabled!
30
+ expect(Grape::Entity::Preloader.enabled?).to be(true)
31
+
32
+ expect do
33
+ Book::Entity.represent(books, serializable: true, only: [:tags_by_association])
34
+ end.to make_database_queries(count: 1)
35
+ .and make_database_queries(
36
+ count: 1,
37
+ matching: /SELECT "tags".* FROM "tags" WHERE "tags"."target_type" = \? AND "tags"."target_id" IN/
38
+ )
39
+ end
40
+
41
+ it '.with_enable' do
42
+ Grape::Entity::Preloader.with_enable do
43
+ expect(Grape::Entity::Preloader.enabled?).to be(true)
44
+
45
+ expect do
46
+ Book::Entity.represent(books, serializable: true, only: [:tags_by_association])
47
+ end.to make_database_queries(count: 1)
48
+ .and make_database_queries(
49
+ count: 1,
50
+ matching: /SELECT "tags".* FROM "tags" WHERE "tags"."target_type" = \? AND "tags"."target_id" IN/
51
+ )
52
+ end
53
+
54
+ expect(Grape::Entity::Preloader.disabled?).to be(true)
55
+ end
56
+ end
57
+
58
+ describe 'disabled' do
59
+ it '.disabled!' do
60
+ Grape::Entity::Preloader.disabled!
61
+ expect(Grape::Entity::Preloader.disabled?).to be(true)
62
+
63
+ expect do
64
+ Book::Entity.represent(books, serializable: true, only: [:tags_by_association])
65
+ end.to make_database_queries(count: 2)
66
+ .and make_database_queries(
67
+ count: 2,
68
+ matching: /SELECT "tags".* FROM "tags" WHERE "tags"."target_id" = \? AND "tags"."target_type" = \?/
69
+ )
70
+ end
71
+
72
+ it '.with_disable' do
73
+ Grape::Entity::Preloader.enabled!
74
+ Grape::Entity::Preloader.with_disable do
75
+ expect(Grape::Entity::Preloader.disabled?).to be(true)
76
+
77
+ expect do
78
+ Book::Entity.represent(books, serializable: true, only: [:tags_by_association])
79
+ end.to make_database_queries(count: 2)
80
+ .and make_database_queries(
81
+ count: 2,
82
+ matching: /SELECT "tags".* FROM "tags" WHERE "tags"."target_id" = \? AND "tags"."target_type" = \?/
83
+ )
84
+ end
85
+ expect(Grape::Entity::Preloader.enabled?).to be(true)
86
+ end
87
+ end
88
+ end
89
+
90
+ describe 'preload' do
91
+ let!(:users) { User.all.load }
92
+ let!(:books) { Book.all.load }
93
+
94
+ describe 'association' do
95
+ it 'single' do
96
+ books = Book.all.load
97
+ expect do
98
+ Book::Entity.represent(books, serializable: true, only: %i[tags_by_association])
99
+ end.to make_database_queries(count: 1)
100
+ .and make_database_queries(count: 1, matching: /book_tags_by_association/)
101
+ end
102
+
103
+ it 'nested' do
104
+ expect do
105
+ User::Entity.represent(
106
+ users,
107
+ serializable: true,
108
+ only: [books_by_association: %i[tags_by_association tags_by_callback]]
109
+ )
110
+ end.to make_database_queries(count: 3)
111
+ .and make_database_queries(count: 1, matching: /user_books_by_association/)
112
+ .and make_database_queries(count: 1, matching: /book_tags_by_association/)
113
+ .and make_database_queries(count: 1, matching: /book_tags_by_callback/)
114
+ end
115
+
116
+ it 'same preload_association(single preload_association after nested preload_association)' do
117
+ options = {
118
+ serializable: true,
119
+ expose_books_count_by_association: true,
120
+ only: %i[books_count_by_association]
121
+ }
122
+
123
+ expect do
124
+ User::Entity.represent(users, options.dup)
125
+ end.to make_database_queries(count: 1)
126
+ .and make_database_queries(count: 1, matching: /user_books_by_association/)
127
+
128
+ users.map(&:reload)
129
+
130
+ options[:only] << { books_by_association: [:tags_by_association] }
131
+ expect do
132
+ User::Entity.represent(users, options.dup)
133
+ end.to make_database_queries(count: 2)
134
+ .and make_database_queries(count: 1, matching: /user_books_by_association/)
135
+ .and make_database_queries(count: 1, matching: /book_tags_by_association/)
136
+ end
137
+ end
138
+
139
+ describe 'callback' do
140
+ it 'single' do
141
+ expect do
142
+ Book::Entity.represent(books, serializable: true, only: %i[tags_by_callback])
143
+ end.to make_database_queries(count: 1)
144
+ .and make_database_queries(count: 1, matching: /book_tags_by_callback/)
145
+ end
146
+
147
+ it 'nested' do
148
+ expect do
149
+ User::Entity.represent(
150
+ users,
151
+ serializable: true,
152
+ only: [books_by_callback: %i[tags_by_association tags_by_callback]]
153
+ )
154
+ end.to make_database_queries(count: 3)
155
+ .and make_database_queries(count: 1, matching: /books_by_callback/)
156
+ .and make_database_queries(count: 1, matching: /book_tags_by_association/)
157
+ .and make_database_queries(count: 1, matching: /book_tags_by_callback/)
158
+ end
159
+ end
160
+
161
+ describe 'condition' do
162
+ it 'true' do
163
+ expect do
164
+ Book::Entity.represent(
165
+ books,
166
+ serializable: true,
167
+ expose_book_tags_count_by_association: true,
168
+ only: %i[tags_count_by_association]
169
+ )
170
+ end.to make_database_queries(count: 1)
171
+ .and make_database_queries(count: 1, matching: /book_tags_by_association/)
172
+ end
173
+
174
+ it 'false' do
175
+ expect do
176
+ Book::Entity.represent(
177
+ books,
178
+ serializable: true,
179
+ expose_book_tags_count_by_association: false,
180
+ only: %i[tags_count_by_association]
181
+ )
182
+ end.to make_database_queries(count: 2)
183
+ .and make_database_queries(count: 2, matching: /book_tags_by_association/)
184
+ end
185
+ end
186
+ end
187
+ end
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'sqlite3'
4
+ require 'active_record'
5
+ require 'db-query-matchers'
6
+ require 'grape/entity/preloader'
7
+
8
+ ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
9
+ # ActiveRecord::Base.logger = Logger.new($stdout)
10
+
11
+ Dir[File.join(File.dirname(__FILE__), 'support', '**', '*.rb')].sort.each { |f| require f }
12
+
13
+ RSpec.configure do |config|
14
+ # Enable flags like --only-failures and --next-failure
15
+ config.example_status_persistence_file_path = '.rspec_status'
16
+
17
+ # Disable RSpec exposing methods globally on `Module` and `main`
18
+ config.disable_monkey_patching!
19
+
20
+ config.expect_with :rspec do |c|
21
+ c.syntax = :expect
22
+ end
23
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ class ApplicationRecord < ActiveRecord::Base
4
+ self.abstract_class = true
5
+ end
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Book < ApplicationRecord
4
+ include Grape::Entity::DSL
5
+
6
+ connection.create_table(:books, if_not_exists: true) do |t|
7
+ t.string :name
8
+ t.references :author
9
+ end
10
+
11
+ belongs_to :author, foreign_key: :author_id, class_name: 'User'
12
+ with_options(class_name: 'Tag', as: :target, dependent: :destroy) do |assoc|
13
+ assoc.has_many :tags_by_association, -> { annotate('book_tags_by_association') }
14
+ assoc.has_many :tags_by_callback, -> { annotate('book_tags_by_callback') }
15
+ end
16
+
17
+ entity do
18
+ expose :name
19
+ expose :tags_by_association, using: 'Tag::Entity', preload_association: :tags_by_association
20
+ expose :tags_by_callback, using: 'Tag::Entity', preload_callback: lambda { |objects, _options|
21
+ ActiveRecord::Associations::Preloader.new(
22
+ records: objects,
23
+ associations: :tags_by_callback
24
+ ).call.first.preloaded_records
25
+ }
26
+ expose :tags_count_by_association, preload_association: :tags_by_association,
27
+ preload_condition: ->(options) { options[:expose_book_tags_count_by_association] } # rubocop:disable Layout/LineLength
28
+ expose :tags_count_by_callback, preload_condition: ->(options) { options[:expose_book_tags_count_by_callback] },
29
+ preload_callback: lambda { |objects, _options|
30
+ ActiveRecord::Associations::Preloader.new(
31
+ records: objects,
32
+ associations: :tags_by_callback
33
+ ).call.first.preloaded_records
34
+ }
35
+
36
+ def tags_count_by_association
37
+ object.tags_by_association.size
38
+ end
39
+
40
+ def tags_count_by_callback
41
+ object.tags_by_callback.size
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Tag < ApplicationRecord
4
+ include Grape::Entity::DSL
5
+
6
+ connection.create_table(:tags, if_not_exists: true) do |t|
7
+ t.string :name
8
+ t.references :target, polymorphic: true
9
+ end
10
+
11
+ belongs_to :target, polymorphic: true
12
+
13
+ entity do
14
+ expose :name
15
+ end
16
+ end
@@ -0,0 +1,73 @@
1
+ # frozen_string_literal: true
2
+
3
+ class User < ApplicationRecord
4
+ include Grape::Entity::DSL
5
+
6
+ connection.create_table(:users, if_not_exists: true) do |t|
7
+ t.string :name
8
+ end
9
+
10
+ with_options(class_name: 'Book', foreign_key: :author_id, dependent: :destroy) do |assoc|
11
+ assoc.has_many :books_by_association, -> { annotate('user_books_by_association') }
12
+ assoc.has_many :books_by_callback, -> { annotate('user_books_by_callback') }
13
+ end
14
+
15
+ with_options(class_name: 'Tag', as: :target, dependent: :destroy) do |assoc|
16
+ assoc.has_many :tags_by_association, -> { annotate('user_tags_by_association') }
17
+ assoc.has_many :tags_by_callback, -> { annotate('user_tags_by_callback') }
18
+ end
19
+
20
+ entity do
21
+ expose :name
22
+
23
+ expose :books_by_association, using: 'Book::Entity', preload_association: :books_by_association
24
+ expose :books_by_callback, using: 'Book::Entity', preload_callback: lambda { |objects, _options|
25
+ ActiveRecord::Associations::Preloader.new(
26
+ records: objects,
27
+ associations: :books_by_callback
28
+ ).call.first.preloaded_records
29
+ }
30
+ expose :books_count_by_association, preload_association: :books_by_association,
31
+ preload_condition: ->(options) { options[:expose_books_count_by_association] }
32
+ expose :books_count_by_callback, preload_condition: ->(options) { options[:expose_books_count_by_callback] },
33
+ preload_callback: lambda { |objects, _options|
34
+ ActiveRecord::Associations::Preloader.new(
35
+ records: objects,
36
+ associations: :books_by_callback
37
+ ).call.first.preloaded_records
38
+ }
39
+
40
+ expose :tags_by_association, using: 'Tag::Entity', preload_association: :tags_by_association
41
+ expose :tags_by_callback, using: 'Tag::Entity', preload_callback: lambda { |objects, _options|
42
+ ActiveRecord::Associations::Preloader.new(
43
+ records: objects,
44
+ associations: :tags_by_callback
45
+ ).call.first.preloaded_records
46
+ }
47
+ expose :tags_count_by_association, preload_association: :tags_by_association,
48
+ preload_condition: ->(options) { options[:expose_user_tags_count_by_association] } # rubocop:disable Layout/LineLength
49
+ expose :tags_count_by_callback, preload_condition: ->(options) { options[:expose_user_tags_count_by_callback] },
50
+ preload_callback: lambda { |objects, _options|
51
+ ActiveRecord::Associations::Preloader.new(
52
+ records: objects,
53
+ associations: :tags_by_callback
54
+ ).call.first.preloaded_records
55
+ }
56
+
57
+ def books_count_by_association
58
+ object.books_by_association.size
59
+ end
60
+
61
+ def books_count_by_callback
62
+ object.books_by_callback.size
63
+ end
64
+
65
+ def tags_count_by_association
66
+ object.tags_by_association.size
67
+ end
68
+
69
+ def tags_count_by_callback
70
+ object.tags_by_callback.size
71
+ end
72
+ end
73
+ end
metadata ADDED
@@ -0,0 +1,78 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: grape-entity-preloader
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - OuYangJinTing
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: grape-entity
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: '1.0'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - "~>"
24
+ - !ruby/object:Gem::Version
25
+ version: '1.0'
26
+ description: Grape::Entity::Preloader allows preload associations and callbacks for
27
+ avoiding N+1 operations in Grape::Entity.
28
+ email:
29
+ - Ou.Yang.Jin.Ting.X@gmail.com
30
+ executables: []
31
+ extensions: []
32
+ extra_rdoc_files: []
33
+ files:
34
+ - ".rspec"
35
+ - CHANGELOG.md
36
+ - CODE_OF_CONDUCT.md
37
+ - LICENSE.txt
38
+ - README.md
39
+ - Rakefile
40
+ - lib/grape/entity/preloader.rb
41
+ - lib/grape/entity/preloader/entity.rb
42
+ - lib/grape/entity/preloader/exposure/base.rb
43
+ - lib/grape/entity/preloader/options.rb
44
+ - lib/grape/entity/preloader/version.rb
45
+ - sig/grape/entity/preloader.rbs
46
+ - spec/grape/entity/preloader_spec.rb
47
+ - spec/n_plus_one_op_spec.rb
48
+ - spec/spec_helper.rb
49
+ - spec/support/models/application_record.rb
50
+ - spec/support/models/book.rb
51
+ - spec/support/models/tag.rb
52
+ - spec/support/models/user.rb
53
+ homepage: https://github.com/OuYangJinTing/grape-entity-preloader
54
+ licenses:
55
+ - MIT
56
+ metadata:
57
+ homepage_uri: https://github.com/OuYangJinTing/grape-entity-preloader
58
+ source_code_uri: https://github.com/OuYangJinTing/grape-entity-preloader
59
+ changelog_uri: https://github.com/OuYangJinTing/grape-entity-preloader/blob/main/CHANGELOG.md
60
+ rdoc_options: []
61
+ require_paths:
62
+ - lib
63
+ required_ruby_version: !ruby/object:Gem::Requirement
64
+ requirements:
65
+ - - ">="
66
+ - !ruby/object:Gem::Version
67
+ version: 3.2.0
68
+ required_rubygems_version: !ruby/object:Gem::Requirement
69
+ requirements:
70
+ - - ">="
71
+ - !ruby/object:Gem::Version
72
+ version: '0'
73
+ requirements: []
74
+ rubygems_version: 3.6.7
75
+ specification_version: 4
76
+ summary: Grape::Entity::Preloader allows preload associations and callbacks for avoiding
77
+ N+1 operations in Grape::Entity.
78
+ test_files: []