【问题标题】:How to refactor case..when in Ruby [closed]如何在 Ruby 中重构 case..when [关闭]
【发布时间】:2017-09-18 09:44:42
【问题描述】:
  def readable
    uptime = (Time.now - self).to_i
    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

Linter 谈到以下错误,如何解决?

【问题讨论】:

  • codereview.stackexchange.com 适合这类问题。
  • 我投票决定将此问题作为题外话结束,因为它是工作代码,应该发布在Code Review
  • 这是我暂时禁用 rubocop 规则 b/c 我同意这是一个非常简洁的实现。

标签: ruby refactoring rubocop reek


【解决方案1】:

查看time_ago_in_words 并随意使用它或其代码。

关于代码指标 - 您的代码非常简单,您应该只提取 uptime 方法。

【讨论】:

  • implementation 没那么简单吧?
  • 当然。没有机会写得更简单。我被提到它只是想着不要重复 Rails :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多