问题描述
我想覆盖 Ruby 的 Range
中的 ..
和 ...
运算符.
I want to override the ..
and ...
operators in Ruby's Range
.
原因是,我正在使用数据库中的无限日期范围.如果你从 Postgres 中取出一个 infinty
日期时间,你会在 Ruby 中得到一个 Float::INFINITY
.
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.
问题在于,我不能使用 Float::INFINITY
作为范围的结尾:
The problem with this is, I cannot use Float::INFINITY
as the end of a range:
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.
为了能够构建范围,您需要使用 DateTime::Infinity.new
代替:
To even be able to construct the range, you need to use DateTime::Infinity.new
instead:
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>
但我每次都需要进行 Float::INFINITY
-> DateTime::Infinity.new
转换:
But I would need to do the the Float::INFINITY
-> DateTime::Infinity.new
conversion every time:
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.
我的建议是简单地覆盖模型中的 end_date
方法:
What I would suggest instead, is to simply override the end_date
method in model:
def end_date
super == Float::INFINITY ? DateTime::Infinity.new : super
end
这基本上是说如果数据库中的 end_date
是 Float::INFINITY
返回 DateTime::Infinity.new
作为 end_date代码>,否则返回数据库中的内容.
This basically says if end_date
in db is Float::INFINITY
return DateTime::Infinity.new
as end_date
, otherwise return what's in database.
这篇关于如何覆盖 .. 和 ... Ruby Ranges 的运算符以接受 Float::INFINITY?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!