如何在Rails中编写增加日助手?

时间:2012-07-29 16:59:10

标签: ruby-on-rails ruby ruby-on-rails-3 refactoring helper

我有下面的帮助,应该把文字放在一天取决于数字:

def day_in_words(number)
    case number
    when 0
      "Sunday"
    when 1
      "Monday"
    when 2
      "Tuesday"
    when 3
      "Wednesday"
    when 4
      "Thursday"
    when 5
      "Friday"
    when 6
      "Saturday"
    when 7
      "Sunday"
    when 8
      "Monday"
    when 9
      "Tuesday"
    when 10
      "Wednesday"
    when 11
      "Thursday"
    ...
    when 16
      "Sunday"
    when 17
      "Monday"
    when 18
      "Tuesday"
    when 19
      "Wednesday"
    when 20
      "Thursday"
    when 21
      "Friday"
    else
      "Unknown Day"
    end
  end

如何重构那个助手?

3 个答案:

答案 0 :(得分:7)

你有没有试过这个 - >

Date::DAYNAMES[number%7]

答案 1 :(得分:1)

您可以使用:

def day_in_words(number)
  return "Unknown Day" if number > 20
  %w[sun mon tue wed thu fri sat].cycle(3).to_a[number]
end

答案 2 :(得分:0)

首先想到的是使用modulo 7作为日期名称数组的索引:

def day_in_words(number)
  return ['Sun','Mon','Tue','Wed','Thurs','Fri','Sat'][number % 7]
end