我知道这看起来微不足道,但假设在Ruby on Rails中,我拥有
document.expire_in = 7.days
我怎样才能打印出可供人类阅读的到期邮件?
"Document will expire in #{document.expire_in}"
=> Document will expire in 7 days
也许可以用 I18n.t
或 I18n.l
唯一可行的方法是
7.天.检查=> "7天"
这是唯一的办法吗?
我在看 ActiveSupport::Duration而看不到答案
谢谢
这并没有回答你的具体问题,但在我看来,你最好是设置过期的日期时间,然后利用 时间的距离_字数.
如果你总是简单的说7天,那为什么不直接写成一个硬编码的字符串呢?
所以在Rails中没有内置的解决方案。我决定使用
7.days.inspect => "7 days"
后来,当项目被翻译出来后,我将会延长 ActiveSupport::Duration
有意义的东西,将转化这些
不过我建议你看看Robert对这个问题的评论。我同意在数据库中保留值的解决方案,例如:"7天",然后从这个值中做一些事情。"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"
下面是一个使用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"