Skip to content

Commit

Permalink
Add Object#in? support for open date ranges
Browse files Browse the repository at this point in the history
This leverages Range#cover? to properly handle beginless and endless
range inclusion checks.
  • Loading branch information
joiggama committed Feb 8, 2023
1 parent d77c3fa commit 47b0aa0
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
18 changes: 13 additions & 5 deletions activesupport/lib/active_support/core_ext/object/inclusion.rb
@@ -1,16 +1,24 @@
# frozen_string_literal: true

class Object
# Returns true if this object is included in the argument. Argument must be
# any object which responds to +#include?+. Usage:
# Returns true if this object is included in the argument.
#
# When argument is a +Range+, +#cover?+ is used to properly handle inclusion
# check within open ranges. Otherwise, argument must be any object which responds
# to +#include?+. Usage:
#
# characters = ["Konata", "Kagami", "Tsukasa"]
# "Konata".in?(characters) # => true
#
# This will throw an +ArgumentError+ if the argument doesn't respond
# to +#include?+.
# For non +Range+ arguments, this will throw an +ArgumentError+ if the argument
# doesn't respond to +#include?+.
def in?(another_object)
another_object.include?(self)
case another_object
when Range
another_object.cover?(self)
else
another_object.include?(self)
end
rescue NoMethodError
raise ArgumentError.new("The parameter passed to #in? must respond to #include?")
end
Expand Down
5 changes: 5 additions & 0 deletions activesupport/test/core_ext/object/inclusion_test.rb
Expand Up @@ -32,6 +32,11 @@ def test_in_set
assert_not 3.in?(s)
end

def test_in_date_range
assert Date.today.in?(..Date.tomorrow)
assert_not Date.today.in?(Date.tomorrow..)
end

module A
end
class B
Expand Down

0 comments on commit 47b0aa0

Please sign in to comment.