4

我知道这看起来微不足道,但可以说在 Ruby on Rails 中我有

document.expire_in = 7.days

如何打印到期消息的人类可读版本?

"Document will expire in #{document.expire_in}"
=> Document will expire in 7 days

也许可以与I18n.tI18n.l

唯一可行的方法是

7.days.inspect => "7 天"

这是唯一的方法吗??

我正在查看ActiveSupport::Duration并且没有看到答案

谢谢

4

3 回答 3

4

这不能回答您的具体问题,但在我看来,您最好设置它过期的日期时间,然后利用distance_of_time_in_words

如果您总是简单地说 7 天,那么为什么不将其写为硬编码字符串呢?

于 2013-03-08T17:09:46.440 回答
4

所以 Rails 中没有内置的解决方案。我决定和

7.days.inspect => "7 days"

稍后,当项目将被翻译时,我将扩展ActiveSupport::Duration一些有意义的东西来翻译这些

但是我建议查看罗伯特对这个问题的评论。我同意在数据库中保存价值的解决方案,例如:“7 天”,然后做一些事情。像翻译单位值

document = Document.new
document.expire_in = "7 days"

document.translated_day

在文档模型(或装饰器)中

class Document < ActiveRecord::Base
  #....

  def translated_day
    timeline = expire_in.split(' ')
    "#{timeline.first} #{I18n.t("timeline.${timeline.last}")}"
  end
  #..
end


#config/locales/svk.yml
svk:
  timeline:
    days: "dni"
于 2013-03-22T16:43:29.960 回答
3

这是一个使用 i18n 解决方案的示例ActiveSupport::Duration#parts

duration.parts.map { |unit, n| I18n.t unit, count: n, scope: 'duration' }.to_sentence

它可以与以下本地化一起使用:

en:
  duration:
    years:
      one: "%{count} year"
      other: "%{count} years"
    months:
      one: "%{count} month"
      other: "%{count} months"
    weeks:
      one: "%{count} week"
      other: "%{count} weeks"
    days:
      one: "%{count} day"
      other: "%{count} days"
    hours:
      one: "%{count} hour"
      other: "%{count} hours"
    minutes:
      one: "%{count} minute"
      other: "%{count} minutes"
    seconds:
      one: "%{count} second"
      other: "%{count} seconds"
于 2020-05-05T11:48:29.070 回答