aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/core_ext/infinite_comparable.rb
diff options
context:
space:
mode:
Diffstat (limited to 'activesupport/lib/active_support/core_ext/infinite_comparable.rb')
-rw-r--r--activesupport/lib/active_support/core_ext/infinite_comparable.rb35
1 files changed, 35 insertions, 0 deletions
diff --git a/activesupport/lib/active_support/core_ext/infinite_comparable.rb b/activesupport/lib/active_support/core_ext/infinite_comparable.rb
new file mode 100644
index 0000000000..b78b2deaad
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/infinite_comparable.rb
@@ -0,0 +1,35 @@
+require 'active_support/concern'
+require 'active_support/core_ext/module/aliasing'
+require 'active_support/core_ext/object/try'
+
+module InfiniteComparable
+ extend ActiveSupport::Concern
+
+ included do
+ alias_method_chain :<=>, :infinity
+ end
+
+ define_method :'<=>_with_infinity' do |other|
+ if other.class == self.class
+ public_send :'<=>_without_infinity', other
+ else
+ infinite = try(:infinite?)
+ other_infinite = other.try(:infinite?)
+
+ # inf <=> inf
+ if infinite && other_infinite
+ infinite <=> other_infinite
+ # not_inf <=> inf
+ elsif other_infinite
+ -other_infinite
+ # inf <=> not_inf
+ elsif infinite
+ infinite
+ else
+ conversion = "to_#{self.class.name.downcase}"
+ other = other.public_send(conversion) if other.respond_to?(conversion)
+ public_send :'<=>_without_infinity', other
+ end
+ end
+ end
+end