简体   繁体   English

如何覆盖Ruby Ranges的..和…运算符以接受Float :: INFINITY?

[英]How can I override the .. and … operators of Ruby Ranges to accept Float::INFINITY?

I want to override the .. and ... operators in Ruby's Range . 我想覆盖Ruby的Range.....运算符。

Reason is, I'm working with infinite date ranges in the database. 原因是,我正在使用数据库中的无限日期范围。 If you pull an infinty datetime out of Postgres, you get a Float::INFINITY in Ruby. 如果从Postgres中提取一个infinty日期时间,则在Ruby中会得到一个Float::INFINITY

The problem with this is, I cannot use Float::INFINITY as the end of a range: 问题是,我不能使用Float::INFINITY作为范围的结尾:

Date.today...Float::INFINITY
=> Wed, 02 Nov 2016...Infinity 

DateTime.now...Float::INFINITY
# ArgumentError: bad value for range

Time.now...Float::INFINITY
# ArgumentError: bad value for range

... yet I use .. and ... syntax quite often in my code. ...但是我在代码中经常使用.....语法。

To even be able to construct the range, you need to use DateTime::Infinity.new instead: 为了甚至能够构造范围,您需要使用DateTime::Infinity.new代替:

Date.today...DateTime::Infinity.new
=> Wed, 02 Nov 2016...#<Date::Infinity:0x007fd82348c698 @d=1> 

DateTime.now...DateTime::Infinity.new
=> Wed, 02 Nov 2016 12:57:07 +0000...#<Date::Infinity:0x007fd82348c698 @d=1> 

Time.now...DateTime::Infinity.new
=> 2016-11-02 12:57:33 +0000...#<Date::Infinity:0x007fd82348c698 @d=1> 

But I would need to do the the Float::INFINITY -> DateTime::Infinity.new conversion every time: 但是我每次都需要进行Float::INFINITY > DateTime::Infinity.new转换:

model.start_time...convert_infinity(model.end_time)

Is there a way I can override the .. and ... operators so that I can incorporate the conversion function and keep the syntactic sugar? 有没有一种方法可以覆盖.....运算符,以便可以合并转换函数并保留语法糖?

I don't think that what you want to do is a correct way of solving such issue. 我认为您要做的不是解决此类问题的正确方法。

What I would suggest instead, is to simply override the end_date method in model: 相反,我建议的是简单地覆盖模型中的end_date方法:

def end_date
  super == Float::INFINITY ? DateTime::Infinity.new : super
end

This basically says if end_date in db is Float::INFINITY return DateTime::Infinity.new as end_date , otherwise return what's in database. 这基本上是说,如果db中的end_dateFloat::INFINITY返回DateTime::Infinity.new作为end_date ,否则返回数据库中的内容。

Ruby 2.6 introduces endless range , which can be used in this manner, for example: Ruby 2.6引入了endless range ,可以以这种方式使用它,例如:

(DateTime.now..)
(DateTime.now...)

This provides a new approach to answering this question. 这为回答这个问题提供了一种新方法。 Hope it's useful for someone! 希望对某人有用!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM