in_time_scope 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: eee76cde212cee461aa7b915b048c5479bc1adc82faa1a57fc4d10e136806eb6
4
+ data.tar.gz: b6de2422411c951e2e1cf3029498755b77c9de73731ed9e24d3d20c0df612d79
5
+ SHA512:
6
+ metadata.gz: 9d9daa7dc0815efde3c0d6a0d6231da6799526fa17be1c96bc22cb76f460ce7e4c84f40ae449760a5e24e86177632b174c94ecf13ec0d3240cae9c4a39ad5721
7
+ data.tar.gz: 337490e629eca19edec0fe0615ee895f67e475258281a173c61e10cf8014a4f185ae72c48fbc07065d7ae29c0b6e9016b547827b83556a4d8c6be3c79c95ec04
data/.rubocop.yml ADDED
@@ -0,0 +1,43 @@
1
+ AllCops:
2
+ TargetRubyVersion: 3.1
3
+ NewCops: enable
4
+ SuggestExtensions: false
5
+
6
+ Style/StringLiterals:
7
+ EnforcedStyle: double_quotes
8
+
9
+ Style/StringLiteralsInInterpolation:
10
+ EnforcedStyle: double_quotes
11
+
12
+ Style/Lambda:
13
+ EnforcedStyle: literal
14
+
15
+ Metrics/AbcSize:
16
+ Enabled: false
17
+
18
+ Metrics/MethodLength:
19
+ Max: 35
20
+
21
+ Metrics/ModuleLength:
22
+ Enabled: false
23
+
24
+ Metrics/CyclomaticComplexity:
25
+ Enabled: false
26
+
27
+ Metrics/PerceivedComplexity:
28
+ Enabled: false
29
+
30
+ Metrics/BlockLength:
31
+ Max: 30
32
+ Exclude:
33
+ - "spec/**/*"
34
+ - "*.gemspec"
35
+
36
+ Layout/LineLength:
37
+ Max: 140
38
+
39
+ Style/Documentation:
40
+ Enabled: false
41
+
42
+ Gemspec/DevelopmentDependencies:
43
+ EnforcedStyle: gemspec
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2026-01-24
4
+
5
+ - Initial release
data/CLAUDE.md ADDED
@@ -0,0 +1,71 @@
1
+ # CLAUDE.md
2
+
3
+ This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
4
+
5
+ ## Project Overview
6
+
7
+ InTimeScope is a Ruby gem that adds time-window scopes to ActiveRecord models. It provides a convenient way to query records that fall within specific time periods (between `start_at` and `end_at` timestamps), with support for nullable columns, custom column names, and multiple scopes per model.
8
+
9
+ ## Commands
10
+
11
+ ```bash
12
+ # Install dependencies
13
+ bin/setup
14
+
15
+ # Run all checks (linting + tests)
16
+ bundle exec rake
17
+
18
+ # Run tests only
19
+ bundle exec rspec
20
+
21
+ # Run a single test file
22
+ bundle exec rspec spec/in_time_scope_spec.rb
23
+
24
+ # Run a specific test by line number
25
+ bundle exec rspec spec/in_time_scope_spec.rb:10
26
+
27
+ # Run linting only
28
+ bundle exec rubocop
29
+
30
+ # Auto-fix linting issues
31
+ bundle exec rubocop -a
32
+
33
+ # Interactive console with gem loaded
34
+ bin/console
35
+
36
+ # Install gem locally
37
+ bundle exec rake install
38
+ ```
39
+
40
+ ## Code Style
41
+
42
+ - Ruby 3.1+ required
43
+ - Use double-quoted strings (enforced by RuboCop)
44
+ - All files must have `# frozen_string_literal: true` header
45
+
46
+ ## Architecture
47
+
48
+ Entry point is `lib/in_time_scope.rb` which defines the `InTimeScope` module. When included in an ActiveRecord model, it provides the `in_time_scope` class method that generates:
49
+
50
+ - Class scope methods: `Model.in_time`, `Model.in_time(timestamp)`
51
+ - Instance methods: `instance.in_time?`, `instance.in_time?(timestamp)`
52
+
53
+ The gem auto-detects column nullability from the database schema to generate optimized SQL queries (simpler queries for NOT NULL columns, NULL-aware queries otherwise).
54
+
55
+ Key configuration options for `in_time_scope`:
56
+ - First argument: scope name (default: `:in_time`)
57
+ - `start_at: { column: Symbol|nil, null: Boolean }` - start column config
58
+ - `end_at: { column: Symbol|nil, null: Boolean }` - end column config
59
+
60
+ Setting `column: nil` disables that boundary, enabling start-only (history) or end-only (expiration) patterns.
61
+
62
+ ## Test Structure
63
+
64
+ Tests use RSpec with SQLite3 in-memory database. Test models are defined in `spec/support/create_test_database.rb`:
65
+
66
+ - `Event` - basic nullable time window
67
+ - `Campaign` - non-nullable time window
68
+ - `Promotion` - custom column names
69
+ - `Article` - multiple scopes
70
+ - `History` - start-only pattern
71
+ - `Coupon` - end-only pattern
@@ -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) 2026 kyohah
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,269 @@
1
+ # InTimeScope
2
+
3
+ TODO: Delete this and the text below, and describe your gem
4
+
5
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/in_time_scope`. To experiment with that code, run `bin/console` for an interactive prompt.
6
+
7
+ ## Installation
8
+
9
+ Install the gem and add to the application's Gemfile by executing:
10
+
11
+ ```bash
12
+ bundle add in_time_scope
13
+ ```
14
+
15
+ If bundler is not being used to manage dependencies, install the gem by executing:
16
+
17
+ ```bash
18
+ gem install in_time_scope
19
+ ```
20
+
21
+ ## Usage
22
+
23
+ ### Basic: Nullable Time Window
24
+ Use the defaults (`start_at` / `end_at`) even when the columns allow `NULL`.
25
+
26
+ ```ruby
27
+ create_table :events do |t|
28
+ t.datetime :start_at, null: true
29
+ t.datetime :end_at, null: true
30
+
31
+ t.timestamps
32
+ end
33
+
34
+ class Event < ActiveRecord::Base
35
+ include InTimeScope
36
+
37
+ # Uses start_at / end_at by default
38
+ in_time_scope
39
+ end
40
+
41
+ Event.in_time
42
+ # => SELECT "events".* FROM "events" WHERE ("events"."start_at" IS NULL OR "events"."start_at" <= '2026-01-24 19:50:05.738232') AND ("events"."end_at" IS NULL OR "events"."end_at" > '2026-01-24 19:50:05.738232') /* loading for pp */ LIMIT $1 [["LIMIT", 11]]
43
+
44
+ # Check at a specific time
45
+ Event.in_time(Time.parse("2024-06-01 12:00:00"))
46
+ # => SELECT "events".* FROM "events" WHERE ("events"."start_at" IS NULL OR "events"."start_at" <= '2024-06-01 12:00:00.000000') AND ("events"."end_at" IS NULL OR "events"."end_at" > '2024-06-01 12:00:00.000000') /* loading for pp */ LIMIT $1 [["LIMIT", 11]]
47
+
48
+ # Is the current time within the window?
49
+ event = Event.first
50
+ event.in_time?
51
+ #=> true or false
52
+
53
+ # Check any arbitrary timestamp
54
+ event.in_time?(Time.parse("2024-06-01 12:00:00"))
55
+ #=> true or false
56
+ ```
57
+
58
+ ### Basic: Non-Nullable Time Window
59
+ When both timestamps are required (no `NULL`s), the generated query is simpler and faster.
60
+
61
+ ```ruby
62
+ create_table :events do |t|
63
+ t.datetime :start_at, null: false
64
+ t.datetime :end_at, null: false
65
+
66
+ t.timestamps
67
+ end
68
+
69
+ # Column metadata is read when Rails boots; SQL is optimized for NOT NULL columns.
70
+ Event.in_time
71
+ # => SELECT "events".* FROM "events" WHERE ("events"."start_at" <= '2026-01-24 19:50:05.738232') AND ("events"."end_at" > '2026-01-24 19:50:05.738232') /* loading for pp */ LIMIT $1 [["LIMIT", 11]]
72
+
73
+ # Check at a specific time
74
+ Event.in_time(Time.parse("2024-06-01 12:00:00"))
75
+ # => SELECT "events".* FROM "events" WHERE ("events"."start_at" <= '2024-06-01 12:00:00.000000') AND ("events"."end_at" > '2024-06-01 12:00:00.000000') /* loading for pp */ LIMIT $1 [["LIMIT", 11]]
76
+
77
+ class Event < ActiveRecord::Base
78
+ include InTimeScope
79
+
80
+ # Explicitly mark columns as NOT NULL (even if the DB allows NULL)
81
+ in_time_scope start_at: { null: false }, end_at: { null: false }
82
+ end
83
+ ```
84
+
85
+ ### Options Reference
86
+ Use these options in `in_time_scope` to customize column behavior.
87
+
88
+ | Option | Applies to | Type | Default | Description | Example |
89
+ | --- | --- | --- | --- | --- | --- |
90
+ | `:scope_name` (1st arg) | in_time | `Symbol` | `:in_time` | Creates a named scope like `published_in_time` | `in_time_scope :published` |
91
+ | `start_at: { column: ... }` | start_at | `Symbol` / `nil` | `:start_at` (or `:"<scope>_start_at"` when `:scope_name` is set) | Use a custom column name; set `nil` to disable `start_at` | `start_at: { column: :available_at }` |
92
+ | `end_at: { column: ... }` | end_at | `Symbol` / `nil` | `:end_at` (or `:"<scope>_end_at"` when `:scope_name` is set) | Use a custom column name; set `nil` to disable `end_at` | `end_at: { column: nil }` |
93
+ | `start_at: { null: ... }` | start_at | `true/false` | auto (schema) | Force NULL-aware vs NOT NULL behavior | `start_at: { null: false }` |
94
+ | `end_at: { null: ... }` | end_at | `true/false` | auto (schema) | Force NULL-aware vs NOT NULL behavior | `end_at: { null: true }` |
95
+
96
+ ### Alternative: Start-Only History (No `end_at`)
97
+ Use this when periods never overlap and you want exactly one "current" row.
98
+
99
+ Assumptions:
100
+ - `start_at` is always present
101
+ - periods never overlap (validated)
102
+ - the latest row is the current one
103
+
104
+ If your table still has an `end_at` column but you want to ignore it, disable it via options:
105
+
106
+ ```ruby
107
+ class Event < ActiveRecord::Base
108
+ include InTimeScope
109
+
110
+ # Ignore end_at even if the column exists
111
+ in_time_scope start_at: { null: false }, end_at: { column: nil }
112
+ end
113
+
114
+ Event.in_time(Time.parse("2024-06-01 12:00:00"))
115
+ # => SELECT "events".* FROM "events" WHERE "events"."start_at" <= '2024-06-01 12:00:00.000000' ORDER BY "events"."start_at" DESC
116
+
117
+ # Use .first to get the most recent single record
118
+ Event.in_time.first
119
+ # => SELECT "events".* FROM "events" WHERE "events"."start_at" <= '...' ORDER BY "events"."start_at" DESC LIMIT 1
120
+ ```
121
+
122
+ With no `end_at`, each row implicitly ends at the next row's `start_at`.
123
+ The scope returns all matching records ordered by `start_at DESC`, so:
124
+ - Use `.first` for a single record
125
+ - Use with `has_one` associations for per-parent record selection
126
+
127
+ Boundary behavior is stable:
128
+ - `start_at <= NOW()` picks the newest row whose start has passed
129
+
130
+ Recommended index:
131
+
132
+ ```sql
133
+ CREATE INDEX index_events_on_start_at ON events (start_at);
134
+ ```
135
+
136
+ ### Alternative: End-Only Expiration (No `start_at`)
137
+ Use this when a record is active immediately and expires at `end_at`.
138
+
139
+ Assumptions:
140
+ - `start_at` is not used (implicit "always active")
141
+ - `end_at` can be `NULL` for "never expires"
142
+
143
+ If your table still has a `start_at` column but you want to ignore it, disable it via options:
144
+
145
+ ```ruby
146
+ class Event < ActiveRecord::Base
147
+ include InTimeScope
148
+
149
+ # Ignore start_at and only use end_at
150
+ in_time_scope start_at: { column: nil }, end_at: { null: true }
151
+ end
152
+
153
+ Event.in_time(Time.parse("2024-06-01 12:00:00"))
154
+ # => SELECT "events".* FROM "events" WHERE ("events"."end_at" IS NULL OR "events"."end_at" > '2024-06-01 12:00:00.000000') /* loading for pp */ LIMIT $1 [["LIMIT", 11]]
155
+ ```
156
+
157
+ To fetch active rows:
158
+
159
+ ```sql
160
+ SELECT *
161
+ FROM events
162
+ WHERE end_at IS NULL OR end_at > NOW();
163
+ ```
164
+
165
+ Recommended index:
166
+
167
+ ```sql
168
+ CREATE INDEX index_events_on_end_at ON events (end_at);
169
+ ```
170
+
171
+ ### Advanced: Custom Columns and Multiple Scopes
172
+ Customize which columns are used and define more than one time window per model.
173
+
174
+ ```ruby
175
+ create_table :events do |t|
176
+ t.datetime :available_at, null: true
177
+ t.datetime :expired_at, null: true
178
+ t.datetime :publish_start_at, null: false
179
+ t.datetime :publish_end_at, null: false
180
+
181
+ t.timestamps
182
+ end
183
+
184
+ class Event < ActiveRecord::Base
185
+ include InTimeScope
186
+
187
+ # Use different column names
188
+ in_time_scope start_at: { column: :available_at }, end_at: { column: :expired_at }
189
+
190
+ # Define an additional scope
191
+ in_time_scope :published, start_at: { column: :publish_start_at, null: false }, end_at: { column: :publish_end_at, null: false }
192
+ end
193
+
194
+ Event.in_time
195
+ # => uses available_at / expired_at
196
+
197
+ Event.published_in_time
198
+ # => uses publish_start_at / publish_end_at
199
+ ```
200
+
201
+ ### Using with `has_one` Associations
202
+
203
+ The start-only pattern provides two scopes for `has_one` associations:
204
+
205
+ #### Simple approach: `in_time` + `order`
206
+
207
+ `in_time` provides WHERE only. Add `order` externally:
208
+
209
+ ```ruby
210
+ class Price < ActiveRecord::Base
211
+ include InTimeScope
212
+ belongs_to :user
213
+
214
+ in_time_scope start_at: { null: false }, end_at: { column: nil }
215
+ end
216
+
217
+ class User < ActiveRecord::Base
218
+ has_many :prices
219
+
220
+ # in_time is WHERE only, add order externally
221
+ has_one :current_price,
222
+ -> { in_time.order(start_at: :desc) },
223
+ class_name: "Price"
224
+ end
225
+ ```
226
+
227
+ This works but loads all matching records into memory when using `includes`.
228
+
229
+ #### Efficient approach: `latest_in_time` (NOT EXISTS) - Recommended
230
+
231
+ ```ruby
232
+ class User < ActiveRecord::Base
233
+ has_many :prices
234
+
235
+ # Uses NOT EXISTS subquery - only loads the latest record per user
236
+ has_one :current_price,
237
+ -> { latest_in_time(:user_id) },
238
+ class_name: "Price"
239
+ end
240
+
241
+ # Direct access
242
+ user.current_price
243
+ # => Returns the most recent price where start_at <= Time.current
244
+
245
+ # Efficient with includes (only fetches latest record per user from DB)
246
+ User.includes(:current_price).each do |user|
247
+ puts user.current_price&.amount
248
+ end
249
+ ```
250
+
251
+ The `latest_in_time(:foreign_key)` scope uses a `NOT EXISTS` subquery to filter at the database level, avoiding loading unnecessary records into memory.
252
+
253
+ ## Development
254
+
255
+ After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
256
+
257
+ 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).
258
+
259
+ ## Contributing
260
+
261
+ Bug reports and pull requests are welcome on GitHub at https://github.com/kyohah/in_time_scope. 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/kyohah/in_time_scope/blob/main/CODE_OF_CONDUCT.md).
262
+
263
+ ## License
264
+
265
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
266
+
267
+ ## Code of Conduct
268
+
269
+ Everyone interacting in the InTimeScope project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/kyohah/in_time_scope/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rubocop/rake_task"
5
+ require "rspec/core/rake_task"
6
+
7
+ RuboCop::RakeTask.new
8
+ RSpec::Core::RakeTask.new(:spec)
9
+
10
+ task default: %i[rubocop spec]
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module InTimeScope
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,191 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_record"
4
+ require_relative "in_time_scope/version"
5
+
6
+ module InTimeScope
7
+ class Error < StandardError; end
8
+
9
+ def self.included(model)
10
+ model.extend ClassMethods
11
+ end
12
+
13
+ module ClassMethods
14
+ def in_time_scope(scope_name = nil, start_at: {}, end_at: {})
15
+ scope_name ||= :in_time
16
+ scope_suffix = scope_name == :in_time ? "" : "_#{scope_name}"
17
+
18
+ start_config = normalize_config(start_at, :"start_at#{scope_suffix}", :start_at)
19
+ end_config = normalize_config(end_at, :"end_at#{scope_suffix}", :end_at)
20
+
21
+ define_scope_methods(scope_name, start_config, end_config)
22
+ end
23
+
24
+ private
25
+
26
+ def normalize_config(config, default_column, fallback_column)
27
+ return { column: nil, null: true } if config[:column].nil? && config.key?(:column)
28
+
29
+ column = config[:column] || default_column
30
+ column = fallback_column unless column_names.include?(column.to_s)
31
+ column = nil unless column_names.include?(column.to_s)
32
+
33
+ null = config.key?(:null) ? config[:null] : column_nullable?(column)
34
+
35
+ { column: column, null: null }
36
+ end
37
+
38
+ def column_nullable?(column_name)
39
+ return true if column_name.nil?
40
+
41
+ col = columns_hash[column_name.to_s]
42
+ col ? col.null : true
43
+ end
44
+
45
+ def define_scope_methods(scope_name, start_config, end_config)
46
+ method_name = scope_name == :in_time ? :in_time : :"#{scope_name}_in_time"
47
+ instance_method_name = :"#{method_name}?"
48
+
49
+ start_column = start_config[:column]
50
+ start_null = start_config[:null]
51
+ end_column = end_config[:column]
52
+ end_null = end_config[:null]
53
+
54
+ # Define class-level scope
55
+ if start_column.nil? && end_column.nil?
56
+ # Both disabled - return all
57
+ scope method_name, ->(_time = Time.current) { all }
58
+ elsif end_column.nil?
59
+ # Start-only pattern (history tracking)
60
+ define_start_only_scope(method_name, start_column, start_null)
61
+ elsif start_column.nil?
62
+ # End-only pattern (expiration)
63
+ define_end_only_scope(method_name, end_column, end_null)
64
+ else
65
+ # Both start and end
66
+ define_full_scope(method_name, start_column, start_null, end_column, end_null)
67
+ end
68
+
69
+ # Define instance method
70
+ define_instance_method(instance_method_name, start_column, start_null, end_column, end_null)
71
+ end
72
+
73
+ def define_start_only_scope(method_name, start_column, start_null)
74
+ # Simple scope - WHERE only, no ORDER BY
75
+ # Users can add .order(start_at: :desc) externally if needed
76
+ if start_null
77
+ scope method_name, ->(time = Time.current) {
78
+ where(arel_table[start_column].eq(nil).or(arel_table[start_column].lteq(time)))
79
+ }
80
+ else
81
+ scope method_name, ->(time = Time.current) {
82
+ where(arel_table[start_column].lteq(time))
83
+ }
84
+ end
85
+
86
+ # Efficient scope for has_one + includes using NOT EXISTS subquery
87
+ # Usage: has_one :current_price, -> { latest_in_time(:user_id) }, class_name: 'Price'
88
+ define_latest_scope(method_name, start_column, start_null)
89
+ end
90
+
91
+ def define_latest_scope(method_name, start_column, start_null)
92
+ latest_method_name = method_name == :in_time ? :latest_in_time : :"latest_#{method_name}_in_time"
93
+ tbl = table_name
94
+ col = start_column
95
+
96
+ # NOT EXISTS approach: select records where no later record exists for the same foreign key
97
+ # SELECT * FROM prices p1 WHERE start_at <= ? AND NOT EXISTS (
98
+ # SELECT 1 FROM prices p2 WHERE p2.user_id = p1.user_id
99
+ # AND p2.start_at <= ? AND p2.start_at > p1.start_at
100
+ # )
101
+ scope latest_method_name, ->(foreign_key, time = Time.current) {
102
+ fk = foreign_key
103
+
104
+ not_exists_sql = if start_null
105
+ <<~SQL.squish
106
+ NOT EXISTS (
107
+ SELECT 1 FROM #{tbl} p2
108
+ WHERE p2.#{fk} = #{tbl}.#{fk}
109
+ AND (p2.#{col} IS NULL OR p2.#{col} <= ?)
110
+ AND (p2.#{col} IS NULL OR p2.#{col} > #{tbl}.#{col} OR #{tbl}.#{col} IS NULL)
111
+ AND p2.id != #{tbl}.id
112
+ )
113
+ SQL
114
+ else
115
+ <<~SQL.squish
116
+ NOT EXISTS (
117
+ SELECT 1 FROM #{tbl} p2
118
+ WHERE p2.#{fk} = #{tbl}.#{fk}
119
+ AND p2.#{col} <= ?
120
+ AND p2.#{col} > #{tbl}.#{col}
121
+ )
122
+ SQL
123
+ end
124
+
125
+ base_condition = if start_null
126
+ where(arel_table[col].eq(nil).or(arel_table[col].lteq(time)))
127
+ else
128
+ where(arel_table[col].lteq(time))
129
+ end
130
+
131
+ base_condition.where(not_exists_sql, time)
132
+ }
133
+ end
134
+
135
+ def define_end_only_scope(method_name, end_column, end_null)
136
+ if end_null
137
+ scope method_name, ->(time = Time.current) {
138
+ where(arel_table[end_column].eq(nil).or(arel_table[end_column].gt(time)))
139
+ }
140
+ else
141
+ scope method_name, ->(time = Time.current) {
142
+ where(arel_table[end_column].gt(time))
143
+ }
144
+ end
145
+ end
146
+
147
+ def define_full_scope(method_name, start_column, start_null, end_column, end_null)
148
+ scope method_name, ->(time = Time.current) {
149
+ start_condition = if start_null
150
+ arel_table[start_column].eq(nil).or(arel_table[start_column].lteq(time))
151
+ else
152
+ arel_table[start_column].lteq(time)
153
+ end
154
+
155
+ end_condition = if end_null
156
+ arel_table[end_column].eq(nil).or(arel_table[end_column].gt(time))
157
+ else
158
+ arel_table[end_column].gt(time)
159
+ end
160
+
161
+ where(start_condition).where(end_condition)
162
+ }
163
+ end
164
+
165
+ def define_instance_method(method_name, start_column, start_null, end_column, end_null)
166
+ define_method(method_name) do |time = Time.current|
167
+ start_ok = if start_column.nil?
168
+ true
169
+ elsif start_null
170
+ send(start_column).nil? || send(start_column) <= time
171
+ else
172
+ send(start_column) <= time
173
+ end
174
+
175
+ end_ok = if end_column.nil?
176
+ true
177
+ elsif end_null
178
+ send(end_column).nil? || send(end_column) > time
179
+ else
180
+ send(end_column) > time
181
+ end
182
+
183
+ start_ok && end_ok
184
+ end
185
+ end
186
+ end
187
+ end
188
+
189
+ ActiveSupport.on_load(:active_record) do
190
+ include InTimeScope
191
+ end
@@ -0,0 +1,4 @@
1
+ module InTimeScope
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,139 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: in_time_scope
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - kyohah
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 2026-01-24 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: '6.0'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - ">="
24
+ - !ruby/object:Gem::Version
25
+ version: '6.0'
26
+ - !ruby/object:Gem::Dependency
27
+ name: irb
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: '0'
33
+ type: :development
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - ">="
38
+ - !ruby/object:Gem::Version
39
+ version: '0'
40
+ - !ruby/object:Gem::Dependency
41
+ name: rake
42
+ requirement: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - "~>"
45
+ - !ruby/object:Gem::Version
46
+ version: '13.0'
47
+ type: :development
48
+ prerelease: false
49
+ version_requirements: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - "~>"
52
+ - !ruby/object:Gem::Version
53
+ version: '13.0'
54
+ - !ruby/object:Gem::Dependency
55
+ name: rspec
56
+ requirement: !ruby/object:Gem::Requirement
57
+ requirements:
58
+ - - ">="
59
+ - !ruby/object:Gem::Version
60
+ version: '0'
61
+ type: :development
62
+ prerelease: false
63
+ version_requirements: !ruby/object:Gem::Requirement
64
+ requirements:
65
+ - - ">="
66
+ - !ruby/object:Gem::Version
67
+ version: '0'
68
+ - !ruby/object:Gem::Dependency
69
+ name: rubocop
70
+ requirement: !ruby/object:Gem::Requirement
71
+ requirements:
72
+ - - "~>"
73
+ - !ruby/object:Gem::Version
74
+ version: '1.21'
75
+ type: :development
76
+ prerelease: false
77
+ version_requirements: !ruby/object:Gem::Requirement
78
+ requirements:
79
+ - - "~>"
80
+ - !ruby/object:Gem::Version
81
+ version: '1.21'
82
+ - !ruby/object:Gem::Dependency
83
+ name: sqlite3
84
+ requirement: !ruby/object:Gem::Requirement
85
+ requirements:
86
+ - - ">="
87
+ - !ruby/object:Gem::Version
88
+ version: '0'
89
+ type: :development
90
+ prerelease: false
91
+ version_requirements: !ruby/object:Gem::Requirement
92
+ requirements:
93
+ - - ">="
94
+ - !ruby/object:Gem::Version
95
+ version: '0'
96
+ description: InTimeScope provides time-window scopes for ActiveRecord models.
97
+ email:
98
+ - 3257272+kyohah@users.noreply.github.com
99
+ executables: []
100
+ extensions: []
101
+ extra_rdoc_files: []
102
+ files:
103
+ - ".rubocop.yml"
104
+ - CHANGELOG.md
105
+ - CLAUDE.md
106
+ - CODE_OF_CONDUCT.md
107
+ - LICENSE.txt
108
+ - README.md
109
+ - Rakefile
110
+ - lib/in_time_scope.rb
111
+ - lib/in_time_scope/version.rb
112
+ - sig/in_time_scope.rbs
113
+ homepage: https://github.com/kyohah/in_time_scope
114
+ licenses:
115
+ - MIT
116
+ metadata:
117
+ allowed_push_host: https://rubygems.org
118
+ rubygems_mfa_required: 'true'
119
+ homepage_uri: https://github.com/kyohah/in_time_scope
120
+ source_code_uri: https://github.com/kyohah/in_time_scope
121
+ changelog_uri: https://github.com/kyohah/in_time_scope/blob/main/CHANGELOG.md
122
+ rdoc_options: []
123
+ require_paths:
124
+ - lib
125
+ required_ruby_version: !ruby/object:Gem::Requirement
126
+ requirements:
127
+ - - ">="
128
+ - !ruby/object:Gem::Version
129
+ version: 3.1.0
130
+ required_rubygems_version: !ruby/object:Gem::Requirement
131
+ requirements:
132
+ - - ">="
133
+ - !ruby/object:Gem::Version
134
+ version: '0'
135
+ requirements: []
136
+ rubygems_version: 3.6.2
137
+ specification_version: 4
138
+ summary: Add time-window scopes to ActiveRecord models
139
+ test_files: []