在我的Ruby应用程序中,我有一个Investment
具有term
属性的实体。
我需要此类来接受用户输入形式为3 Years
或的字符串36 months
。我想要的是将输入转换为月数,将term
属性设置为该时间段,然后确定到期日。
到目前为止,我已经尝试使用Active Support和Chronic,但是API不支持此功能。
该吸气剂有效:
def term
if term =~ /year[s]?/i
term = term.to_i * 12
else term =~ /month[s]?/i
term = term.to_i
end
end
但是在Ruby中是否有更优雅的方法可以做到这一点?
Ruby没有内置任何表示“时间跨度”的内容(某些其他语言则有)。但是,有一个针对它timespan
的库(),尽管对于您的情况可能有点过大。
您提到chronic
不支持这一点。但是,为什么不自己计算时差呢?
require 'chronic'
input = '2 years'
then = Chronic.parse(input + ' ago')
now = Time.now
# Now we just calculate the number of months
term = (now.year * 12 + now.month) - (then.year * 12 + then.month)
这样,您可以灵活地进行chronic
解析,而您仍然不需要太多代码。
或者只是继续使用timespan
库。
require 'timespan'
term = Timespan.new('2 years').to_months
# Boom.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句