Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cop idea: Rails/WhereBetween #689

Closed
pirj opened this issue Apr 7, 2022 · 4 comments · Fixed by #1272
Closed

Cop idea: Rails/WhereBetween #689

pirj opened this issue Apr 7, 2022 · 4 comments · Fixed by #1272
Labels
feature request Request for new functionality

Comments

@pirj
Copy link
Member

pirj commented Apr 7, 2022

Problem

User.where("created_at > ?", 30.days.ago).where("created_at < ?", 7.days.ago)

Describe the solution you'd like

Add a cop that would suggest using ranges instead:

User.where(created_at: 7.days.ago..30.days.ago)

Describe alternatives you've considered

Nothing specifically. Personally, I often choose to use ranges even when the constraint is just on one side of the range:

- User.where("created_at > ?", 30.days.ago)
+ User.where(created_at: 30.days.ago..)

Additional context

This is used in the wild, see e.g.

# gitlabhq/app/models/release.rb
scope :released_within_2hrs, -> { where(released_at: Time.zone.now - 1.hour..Time.zone.now + 1.hour) }

could be safely simplified to:

scope :released_within_2hrs, -> { where(released_at: 1.hour.ago..1.hour.from_now) }
@koic
Copy link
Member

koic commented May 2, 2022

Looks good to me. I don't remember the version clearly, but there would have been minimum Rails versions that supported begginless and endless ranges respectively. Anyway it would be better to be shown in the Rails Style Guide first :-)

@koic koic added the feature request Request for new functionality label May 2, 2022
@pirj
Copy link
Member Author

pirj commented May 2, 2022

It seems to be supported since Rails 4.0.0.

@koic
Copy link
Member

koic commented May 3, 2022

FYI, Rails 6.0 or later is required for endless range in Ruby 2.6 syntax and beginless range in Ruby 2.7 syntax:

So, non-abbreviation range syntax is fine, but these abbreviation syntax will need to be noted.

@fatkodima
Copy link
Contributor

For anyone interested, implemented a PR to address this.

@koic koic closed this as completed in #1272 May 2, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature request Request for new functionality
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants