5

Open Ranges Are Now Supported By The Object#in? Method In Rails

 11 months ago
source link: https://blog.saeloun.com/2023/08/23/open-ranges-are-now-supported-by-object-in/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Open Ranges Are Now Supported By The Object#in? Method In Rails

Aug 23, 2023

authorImgPrasanth Chaduvula

authorImg

Prasanth Chaduvula

I'm a React, Javascript & Rails full-stack Software Engineer. I have been working remotely for the past two years in a remote village. Before joining as a Software Engineer I founded kwiq - a hyperlocal delivery startup to deliver things in remote villages.

1 minute read

Object#in?(another_object) method is not part of the Ruby standard library. Thanks to Rails, it’s a convenience method added to the Object class to check if an object is included in another object.

This method returns true if the calling object is found within the argument provided. The argument must be any object that responds to the #include? method, which is a common method used to determine whether a collection or data structure contains a specific element.

fruits = ["Apple", "Mango", "Orange"]
"Apple".in?(fruits) # => true

Before

Verifying objects like strings, numbers, and hash works properly with Object#in? but if we use Object#in? to check if a date is present in an open date range, in Ruby 3.1, it never provides a result owing to the infinite loop, on the other hand, in Ruby 3.2, it raises a TypeError.

irb(main):001:0> Date.today.in?(Date.tomorrow..) 
=> .rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/activesupport-7.0.4.3/lib/active_support/core_ext/range/compare_range.rb:51:in 

`include?': cannot determine inclusion in beginless/endless ranges (TypeError)
irb(main):002:0> 

To check if a date is present in an open date range, we should use the cover? method instead. The cover? method will return true if the date is within the range, and false otherwise.

((Date.today + 1)..).cover?(Date.today) #=> false, immediately

After

In the upcoming version of Rails, it is possible to check if a date is present in an open date range with Object#in?

This Pull Request changes Object#in? behavior to properly handle open date ranges i.e. beginless and endless ranges.

Under the hood Object#in? leverages Range#cover? instead of Range#include to properly handle beginless and endless date range inclusion checks.

Date.today.in?(Date.tomorrow..) => false
((Date.today + 1)..).in?(Date.today..) => true

Share this post!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK