DRY查看strftime调用

时间:2016-10-25 13:42:08

标签: ruby-on-rails ruby

我有一个我的模型的视图,其中渲染了许多日期字段。

我想要做的是在我拥有的每个日期字段上调用strftime('%d.%m.%Y %H:%M')

- @items.each do |item| 
  = item.date_field.strftime('%d.%m.%Y %H:%M') 
  = item.date_field1.strftime('%d.%m.%Y %H:%M')

关于如何干这个的任何想法?我尝试在我的模型中制作to_s方法,但不幸的是,这不起作用。

更新

我定义了这个方法:

def to_s(date)
  send(date).strftime('%d.%m.%Y %H:%M')
end

所以我可以:

- @items.each do |item| 
  = item.to_s(:date_field)
  = item.to_s(:date_field1)

1 个答案:

答案 0 :(得分:4)

您可以创建一个帮助程序(如果您在应用程序范围内使用它,则在application_helper.rb中)

选项1

def customized_time_format(time)
  time.strftime('%d.%m.%Y %H:%M')
end

并在您的观点中使用它

- @items.each do |item| 
  = customized_time_format(item.date_field)
  = customized_time_format(item.date_field1)

<强>选项2

# config/locales/en.yml
en:
  time:
    formats:
      customized: '%d.%m.%Y %H:%M'

并使用它

- @items.each do |item| 
  = l(item.date_field, format: :customized)
  = l(item.date_field1, format: :customized)