Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby on Rails | 日付フォーマット用のヘルパーを作成

概要

日付フォーマット用のヘルパーを作成

内容

日付フォーマット用のヘルパーを作成します。

サンプル

ヘルパー

app/helpers/application_helper.rb

module ApplicationHelper
  def show_dat(time)
    return time unless time
    time.strftime("%Y/%m/%d")
  end

  def show_at(time)
    return time unless time
    time.strftime("%Y/%m/%d %H:%M:%S")
  end
end
Viewから利用
%h1 Book#list
%p Find me in app/views/book/list.html.haml
%hr/ 
%table 
  %tr 
    %th id
    %th name
    %th isbn
    %th price
    %th created_at
    %th updated_at
  -@books.each do |b|
    %tr 
      = content_tag :td, b.id
      = content_tag :td, b.name
      = content_tag :td, b.isbn
      = content_tag :td, b.price
      = content_tag :td, show_dat(b.created_at)
      = content_tag :td, show_at(b.updated_at)

画像

利用前

利用後