# extend Time class for readable method
class Time
def readable
case uptime
when 0 then 'just now'
when 1 then 'uptime second ago'
when 2..59 then uptime.to_s + ' seconds ago'
when 60..119 then 'uptime minute ago' # 120 = 2 minutes
when 120..3540 then (uptime / 60).to_i.to_s + ' minutes ago'
when 3541..7100 then 'an hour ago' # 3600 = 1 hour
when 7101..82_800 then ((uptime + 99) / 3600).to_i.to_s + ' hours ago'
when 82_801..172_000 then 'uptime day ago' # 86400 = 1 day
else ((uptime + 800) / 86_400).to_i.to_s + ' days ago'
end
end
private
def uptime
(Time.now - self).to_i
end
endLinter会引发以下警告。怎么解决这个问题呢?
发布于 2017-09-18 12:48:45
请记住,linter只能够查看代码是如何编写的,而不能查看它实际在做什么,所以switch语句(或与Ruby类似的case语句)是完全没有问题的。
一个测试许多条件的开关肯定是长时间的,没有什么你能做的。您得到的每一个警告都是测试8个值的直接后果。
我想说,这是一个典型的例子,在这种情况下,你只是不浪费你的时间,试图让林特快乐。提取方法会把事情弄得乱七八糟,看上去很傻。
我现在能想到的唯一可行的选择是将这些范围与它们可读的描述放在某种散列中,并从其中检索值。但这是一个折衷方案:如果这个方法经常被调用,您可以在每次调用时实例化另一个对象。
我说你忽略了linter在这种情况下说的话,或者调整它的默认设置,使它不那么烦人。
你的方法很好,我很清楚它的意图,而且它没有做任何复杂的事情。不要为了取悦一个一开始就不懂你的代码的工具而陷入困境。
发布于 2017-09-19 04:30:54
如果您使用的是Rails或ActiveSupport,那么有一个内置的非常类似的time_ago_in_words。
降低复杂性的一种方法是:
def readable
up = uptime
case up
when 0 then 'just now'
when 1..59 then pluralize(up, 'second', 'a')
when 2..3540 then pluralize(up/60, 'minute', 'a')
when 3541..82_800 then pluralize(up/3600, 'hour', 'an)
else pluralize(up/86_400, 'day', 'a')
end
end
# This also mimics the Rails method
def pluralize(quantity, noun, article)
number = quantity == 0 ? 'no' : quantity == 1 ? article : quantity
plural = quantity != 1 ? 's' : ''
"#{number} #{noun}#{plural} ago"
end为了进一步降低复杂性,您可以将范围存储在散列中并遍历它。
RANGES = [ { limit:60, divisor: 1, unit:'second'},
{ limit: 3600, divisor:60, unit:'minute'},
...https://codereview.stackexchange.com/questions/175958
复制相似问题