activerecord_scoped_includes 0.0.1

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: 3ac5b6dd0abbbee28197e833e5529e24ed4be9484d03ef1aff33587d73ca73d4
4
+ data.tar.gz: 1336aa9325d5adc2b4e76a49fe623da50deedbd5b0fb187ed7d486b9077e8913
5
+ SHA512:
6
+ metadata.gz: a1f0352a9f9922b0ecc8d7c7e24552616817fda52794eab359b480b0aca70292df77dd7b3e5b04d37876567189c102464082e34b48ba32fbc95f23769bfe3f7d
7
+ data.tar.gz: 070a74e8e79985c297d250630558a40327025122e9c92717ff9715b026fe4ed7691443bbf64c65d5178fedd9a2a71edce1377c0320f3784ff64419b39e38664a
data/CHANGELOG.md ADDED
@@ -0,0 +1,8 @@
1
+ # Changelog
2
+
3
+ ## 0.0.1 (2026-11-18)
4
+
5
+ - Initial release: a scope as the value of an association in `includes`, `preload` and `eager_load`, as a lambda or a relation.
6
+ - Scopes can select columns, include associations and enable `strict_loading`, and raise an `ArgumentError` for anything that filters or sorts records.
7
+ - Add the keys that link records to their owners to scopes that select columns.
8
+ - Supports Active Record 7.2, 8.0, 8.1 and main.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Maximo Mussini
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,191 @@
1
+ <h1 align="center">
2
+ Scoped Includes
3
+ <p align="center">
4
+ <a href="https://github.com/ElMassimo/activerecord_scoped_includes/actions"><img alt="Build Status" src="https://github.com/ElMassimo/activerecord_scoped_includes/workflows/build/badge.svg"/></a>
5
+ <a href="https://github.com/ElMassimo/activerecord_scoped_includes/blob/main/LICENSE.txt"><img alt="License" src="https://img.shields.io/badge/license-MIT-428F7E.svg"/></a>
6
+ </p>
7
+ </h1>
8
+
9
+ [Active Record]: https://guides.rubyonrails.org/active_record_basics.html
10
+ [deferred_columns]: https://github.com/ElMassimo/deferred_columns
11
+ [mongoid_includes]: https://github.com/ElMassimo/mongoid_includes
12
+ [nested_select]: https://github.com/alekseyl/nested_select
13
+ [Sequel]: https://sequel.jeremyevans.net/rdoc/files/doc/advanced_associations_rdoc.html
14
+ [Issues]: https://github.com/ElMassimo/activerecord_scoped_includes/issues
15
+
16
+ Choose the columns an [Active Record] association loads, right where you include it.
17
+
18
+ ```ruby
19
+ Album.includes(songs: -> { select(:id, :name) })
20
+ # SELECT "albums".* FROM "albums"
21
+ # SELECT "songs"."id", "songs"."name", "songs"."album_id" FROM "songs" WHERE "songs"."album_id" IN (1, 2)
22
+ ```
23
+
24
+ The records load into the association itself, so `album.songs` has them, and code that reads it doesn't need to know which columns were loaded or under which name.
25
+
26
+ ## Why? 🤔
27
+
28
+ To load an association with different columns, Rails needs another association:
29
+
30
+ ```ruby
31
+ class Album < ApplicationRecord
32
+ has_many :songs
33
+ has_many :song_titles, -> { select(:id, :name, :album_id) }, class_name: "Song"
34
+ end
35
+ ```
36
+
37
+ Each variant needs a name, and the code that reads the records has to pick the right one. When a page loads one variant and a component reads the other, the same records are loaded twice.
38
+
39
+ This library lets the query decide how the association is loaded, in the same `includes` call that loads it.
40
+
41
+ ## Features ⚡️
42
+
43
+ - A scope as the value of an association, in `includes`, `preload` and `eager_load`
44
+ - Accepts a lambda, as in association scopes, or a relation
45
+ - Nested includes go inside the scope, so each association keeps its own shape
46
+ - Adds the keys that link records to their owners, which a `select` can easily leave out
47
+ - Works with `has_many :through`, `belongs_to`, `strict_loading` and `Preloader`
48
+ - Works with [deferred_columns], to opt into deferred columns per association
49
+
50
+ ## Installation 💿
51
+
52
+ Add this line to your application's Gemfile:
53
+
54
+ ```ruby
55
+ gem 'activerecord_scoped_includes'
56
+ ```
57
+
58
+ And then run:
59
+
60
+ $ bundle install
61
+
62
+ ## Usage 🚀
63
+
64
+ ### Selecting columns
65
+
66
+ Pass a scope as the value of an association:
67
+
68
+ ```ruby
69
+ Album.includes(songs: -> { select(:name, :track) })
70
+ Album.preload(songs: Song.select(:name, :track))
71
+ ```
72
+
73
+ A lambda is evaluated on the associated model, like an association scope, while a relation can be built anywhere and reused:
74
+
75
+ ```ruby
76
+ SONG_TITLES = Song.select(:name, :track)
77
+
78
+ Album.includes(songs: SONG_TITLES)
79
+ ```
80
+
81
+ It works the same with `eager_load`, and with `includes` when it eager loads:
82
+
83
+ ```ruby
84
+ Album.eager_load(songs: -> { select(:name) })
85
+ Album.includes(songs: -> { select(:name) }).where(songs: { track: 1..3 })
86
+ ```
87
+
88
+ When eager loading, the scope can only select columns of the table, so `select("UPPER(name) AS name")` raises an `ArgumentError`.
89
+
90
+ ### Keys
91
+
92
+ A select doesn't need to list the keys that link each record to its owner, such as `album_id` above.
93
+
94
+ In plain Rails, leaving them out of an association scope loads no records, without raising. This library adds them to the select.
95
+
96
+ ### Nesting includes
97
+
98
+ Include associations of the scoped association inside the scope:
99
+
100
+ ```ruby
101
+ Artist.includes(albums: Album.select(:name).includes(songs: -> { select(:name) }))
102
+ ```
103
+
104
+ Associations without a scope can be mixed in as usual:
105
+
106
+ ```ruby
107
+ Song.includes(:playlist_entries, album: -> { select(:name) })
108
+ ```
109
+
110
+ ### Only the shape, not the records
111
+
112
+ A scope can select columns, include associations, and enable `strict_loading`.
113
+
114
+ It can't filter or sort the records, since the association would then hold only some of its records, and other code reading it would get a partial list:
115
+
116
+ ```ruby
117
+ Album.includes(songs: -> { where(track: 1) })
118
+ # ArgumentError: A scope in includes can only select columns or include associations, but this one uses where.
119
+ # To load only some of the records, define an association with that scope instead.
120
+ ```
121
+
122
+ Define an association for those instead, as usual:
123
+
124
+ ```ruby
125
+ has_many :opening_tracks, -> { where(track: 1) }, class_name: "Song"
126
+ ```
127
+
128
+ ### With deferred_columns
129
+
130
+ The scope can opt into the columns that [deferred_columns] leaves out:
131
+
132
+ ```ruby
133
+ Album.includes(songs: -> { with_deferred(:lyrics) })
134
+ ```
135
+
136
+ This loads the lyrics into `album.songs`, instead of a separate `songs_with_lyrics` association. The opt-ins add up with those of the association scope:
137
+
138
+ ```ruby
139
+ Album.eager_load(songs_with_lyrics: -> { with_deferred(:waveform) }) # lyrics and waveform
140
+ ```
141
+
142
+ ### Associations that are already loaded
143
+
144
+ Like Rails, the preloader keeps the records of an association that is already loaded, so their columns stay as they were.
145
+
146
+ ## How it works 🔧
147
+
148
+ `includes` and `preload` build a tree of associations with `Preloader::Branch`. When the value of an association is a scope, its nested includes become the children of the branch, and the rest of the scope is merged into the scope of the loader, the same way `Preloader.new(scope:)` applies a scope to every association.
149
+
150
+ `eager_load` builds a `JoinDependency` instead, which selects the column names of each joined model. When the association has a scope, those are the columns its `SELECT` would list, so selects and opt-ins from other libraries apply as well.
151
+
152
+ Both are private APIs of Active Record, so the library is tested against every supported version, including `main`.
153
+
154
+ ## Compatibility
155
+
156
+ - Ruby 3.1 or newer
157
+ - Active Record 7.2, 8.0, 8.1 and `main`
158
+ - Tested on SQLite and PostgreSQL
159
+
160
+ ## Running tests 🧪
161
+
162
+ ```sh
163
+ bundle install
164
+ bin/rspec
165
+ ```
166
+
167
+ Some tests check that it works along with [deferred_columns]. They use a checkout in a sibling folder (`../deferred_columns`) when there's one, and the released gem otherwise.
168
+
169
+ To run the tests against a specific version of Rails, set `BUNDLE_GEMFILE` to one of the files in `gemfiles`:
170
+
171
+ ```sh
172
+ BUNDLE_GEMFILE=gemfiles/Gemfile-rails.7.2.x bundle install
173
+ BUNDLE_GEMFILE=gemfiles/Gemfile-rails.7.2.x bin/rspec
174
+ ```
175
+
176
+ The tests run on an in-memory SQLite database by default. To run them on PostgreSQL, set `DATABASE_URL`:
177
+
178
+ ```sh
179
+ createdb activerecord_scoped_includes_test
180
+ DATABASE_URL=postgres:///activerecord_scoped_includes_test bin/rspec
181
+ ```
182
+
183
+ ## Acknowledgements 🙏
184
+
185
+ - [mongoid_includes], whose `with:` option customizes an included association in Mongoid
186
+ - [nested_select], which selects columns of preloaded associations with `select(songs: [:name])`
187
+ - [Sequel], whose `eager` takes a proc per association to customize its dataset
188
+
189
+ ## License
190
+
191
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
@@ -0,0 +1,69 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveRecord
4
+ module ScopedIncludes
5
+ # `eager_load`, and `includes` when it eager loads.
6
+ module JoinDependency
7
+ def self.prepended(base)
8
+ base.singleton_class.prepend(ClassMethods)
9
+ end
10
+
11
+ module ClassMethods
12
+ # Turns the associations into a tree, keeping the scope of each association.
13
+ def walk_tree(associations, hash)
14
+ return super unless associations.is_a?(Hash) && associations.each_value.any? { |value| ScopedIncludes.scope?(value) }
15
+
16
+ associations.each do |name, value|
17
+ next walk_tree({ name => value }, hash) unless ScopedIncludes.scope?(value)
18
+
19
+ children = hash[name] ||= {}
20
+ children.instance_variable_set(:@includes_scope, value)
21
+ walk_tree(ScopedIncludes.nested(value), children)
22
+ end
23
+ end
24
+ end
25
+
26
+ # A table joined by `eager_load`.
27
+ module JoinAssociation
28
+ attr_reader :includes_scope
29
+
30
+ def includes_scope=(scope)
31
+ @includes_scope = scope.except(:includes, :preload, :eager_load)
32
+ end
33
+
34
+ # The columns of the association scope merged with the includes scope, as
35
+ # its SELECT would list them, plus the primary key to tell records apart.
36
+ def column_names
37
+ includes_scope ? includes_column_names : super
38
+ end
39
+
40
+ private
41
+
42
+ def includes_column_names
43
+ @includes_column_names ||= begin
44
+ scope = reflection.scope ? reflection.scope_for(base_klass.unscoped).merge(includes_scope) : includes_scope
45
+ scope.arel.projections.flat_map { |projection| projected_columns(projection) } | [base_klass.primary_key]
46
+ end
47
+ end
48
+
49
+ def projected_columns(projection)
50
+ if projection.is_a?(Arel::Attributes::Attribute) && projection.relation.name == base_klass.table_name
51
+ projection.name == Arel.star ? base_klass.column_names : [projection.name.to_s]
52
+ else
53
+ selected = projection.is_a?(Arel::Attributes::Attribute) ? "#{projection.relation.name}.#{projection.name}" : projection.to_s
54
+ raise ArgumentError, "When eager loading, a scope in includes can only select columns of #{base_klass.table_name}, got: #{selected}"
55
+ end
56
+ end
57
+ end
58
+
59
+ private
60
+
61
+ def build(associations, base_klass)
62
+ super.each_with_index do |join, index|
63
+ scope = associations.values[index].instance_variable_get(:@includes_scope)
64
+ join.includes_scope = ScopedIncludes.resolve(scope, join.base_klass) if scope
65
+ end
66
+ end
67
+ end
68
+ end
69
+ end
@@ -0,0 +1,58 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveRecord
4
+ module ScopedIncludes
5
+ # `preload`, and `includes` when it doesn't eager load.
6
+ module Preloader
7
+ # A node in the tree of associations to preload.
8
+ module Branch
9
+ # Takes the scope out of the children, which become the associations it includes.
10
+ def initialize(association:, children:, parent:, associate_by_default:, scope:)
11
+ includes_scope = children if ScopedIncludes.scope?(children)
12
+ children = ScopedIncludes.nested(includes_scope) if includes_scope
13
+ super # with the reassigned children
14
+ @includes_scope = includes_scope
15
+ end
16
+
17
+ # The scope of each loader, which applies on top of the association scope.
18
+ def scope
19
+ return super unless @includes_scope && @includes_reflection
20
+
21
+ (@includes_scopes ||= {})[@includes_reflection] ||= begin
22
+ scope = ScopedIncludes.resolve(@includes_scope, @includes_reflection.klass).except(:includes, :preload, :eager_load)
23
+ preload_scope = super
24
+ if preload_scope.is_a?(ActiveRecord::Relation)
25
+ preload_scope.merge(scope)
26
+ elsif preload_scope&.strict_loading_value
27
+ scope.strict_loading
28
+ else
29
+ scope
30
+ end
31
+ end
32
+ end
33
+
34
+ # Remembers the reflection, since each target model resolves the scope separately.
35
+ def preloaders_for_reflection(reflection, records)
36
+ @includes_reflection = reflection
37
+ super
38
+ end
39
+ end
40
+
41
+ # Loads the records of an association.
42
+ module Association
43
+ private
44
+
45
+ # A scope that selects columns still needs the keys that link each record to its owner.
46
+ def build_scope
47
+ scope = super
48
+ # Through loaders pass their scope on to the loaders of the source association.
49
+ return scope if scope.select_values.empty? || is_a?(ActiveRecord::Associations::Preloader::ThroughAssociation)
50
+
51
+ key = respond_to?(:destination_key_name, true) ? destination_key_name : association_key_name # renamed in Rails 8.2
52
+ keys = [*key, *klass.primary_key].map(&:to_s) - scope.select_values.map(&:to_s)
53
+ keys.any? ? scope.select(*keys) : scope
54
+ end
55
+ end
56
+ end
57
+ end
58
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveRecord
4
+ module ScopedIncludes
5
+ VERSION = '0.0.1'
6
+ end
7
+ end
@@ -0,0 +1,54 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'active_record'
4
+ require 'active_record/scoped_includes/version'
5
+
6
+ module ActiveRecord
7
+ # Lets `includes`, `preload` and `eager_load` take a scope as the value of an
8
+ # association, to choose the columns it loads and the associations it includes.
9
+ #
10
+ # Album.includes(songs: -> { select(:id, :name) })
11
+ # Album.preload(songs: Song.with_deferred(:lyrics).includes(:playlist_entries))
12
+ #
13
+ # The records still load into the association itself, so code reading
14
+ # `album.songs` gets them without a second association that loads them again.
15
+ module ScopedIncludes
16
+ # The parts of a scope that change how each record is loaded, but not which
17
+ # records are, so the association always holds all of its records.
18
+ SHAPE_VALUES = %i[select extending includes preload eager_load strict_loading].freeze
19
+
20
+ # Whether the value of an association in `includes` is a scope.
21
+ def self.scope?(value)
22
+ value.is_a?(ActiveRecord::Relation) || value.is_a?(Proc)
23
+ end
24
+
25
+ # The relation for a scope, which can be a relation or a lambda evaluated on
26
+ # the model, as in association scopes.
27
+ def self.resolve(scope, model)
28
+ scope = model.unscoped.instance_exec(&scope) if scope.is_a?(Proc)
29
+ unsupported = scope.values.keys - SHAPE_VALUES
30
+ return scope if unsupported.empty?
31
+
32
+ raise ArgumentError,
33
+ "A scope in includes can only select columns or include associations, but this one uses #{unsupported.join(', ')}. " \
34
+ 'To load only some of the records, define an association with that scope instead.'
35
+ end
36
+
37
+ # The associations a scope includes, which become the children of its association.
38
+ def self.nested(scope)
39
+ return [] unless scope.is_a?(ActiveRecord::Relation)
40
+
41
+ [*scope.includes_values, *scope.preload_values, *scope.eager_load_values]
42
+ end
43
+ end
44
+ end
45
+
46
+ require 'active_record/scoped_includes/preloader'
47
+ require 'active_record/scoped_includes/join_dependency'
48
+
49
+ ActiveSupport.on_load(:active_record) do
50
+ ActiveRecord::Associations::Preloader::Branch.prepend(ActiveRecord::ScopedIncludes::Preloader::Branch)
51
+ ActiveRecord::Associations::Preloader::Association.prepend(ActiveRecord::ScopedIncludes::Preloader::Association)
52
+ ActiveRecord::Associations::JoinDependency.prepend(ActiveRecord::ScopedIncludes::JoinDependency)
53
+ ActiveRecord::Associations::JoinDependency::JoinAssociation.prepend(ActiveRecord::ScopedIncludes::JoinDependency::JoinAssociation)
54
+ end
metadata ADDED
@@ -0,0 +1,66 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: activerecord_scoped_includes
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Maximo Mussini
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: activerecord
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: '7.2'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - ">="
24
+ - !ruby/object:Gem::Version
25
+ version: '7.2'
26
+ description: activerecord_scoped_includes lets includes, preload and eager_load take
27
+ a scope for each association, to select columns or nest includes without defining
28
+ another association.
29
+ email:
30
+ - maximomussini@gmail.com
31
+ executables: []
32
+ extensions: []
33
+ extra_rdoc_files: []
34
+ files:
35
+ - CHANGELOG.md
36
+ - LICENSE.txt
37
+ - README.md
38
+ - lib/active_record/scoped_includes/join_dependency.rb
39
+ - lib/active_record/scoped_includes/preloader.rb
40
+ - lib/active_record/scoped_includes/version.rb
41
+ - lib/activerecord_scoped_includes.rb
42
+ homepage: https://github.com/ElMassimo/activerecord_scoped_includes
43
+ licenses:
44
+ - MIT
45
+ metadata:
46
+ source_code_uri: https://github.com/ElMassimo/activerecord_scoped_includes
47
+ changelog_uri: https://github.com/ElMassimo/activerecord_scoped_includes/blob/main/CHANGELOG.md
48
+ rubygems_mfa_required: 'true'
49
+ rdoc_options: []
50
+ require_paths:
51
+ - lib
52
+ required_ruby_version: !ruby/object:Gem::Requirement
53
+ requirements:
54
+ - - ">="
55
+ - !ruby/object:Gem::Version
56
+ version: 3.1.0
57
+ required_rubygems_version: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ requirements: []
63
+ rubygems_version: 4.0.20
64
+ specification_version: 4
65
+ summary: Choose the columns an association loads, right where you include it.
66
+ test_files: []