8
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Railsでdate_selectの和暦版入力フォームをつくる

Posted at

date_selectで生成したhtmlを受け取って、年の部分を和暦表示にするヘルパーを作った。
ちょっと無理矢理感があるけど、お手軽。

app/helpers/application_helper.rb
  def date_select_ja(src_html)
    dst_html = src_html.gsub(/>\d{4}</) do |m|
      year = m.match(/>(\d{4})</)[1].to_i
      year_ja = case year
        when 0..1911
          "明治#{year - 1867}"
        when 1912
          "明治45/大正元年"
        when 1913..1925
          "大正#{year - 1911}"
        when 1926                                                                   
          "大正15/昭和元年"
        when 1927..1988
          "昭和#{year - 1925}"
        when 1989
          "昭和64/平成元年"
        else
          "平成#{year - 1988}"
      end
      ">#{year_ja} (#{year})<"
    end
    dst_html.html_safe
  end

こんな感じで使う。

app/views/hoge.html.erb
    <%= date_select_ja(f.date_select(:date)) %>

表示するときには、tomiacannondale/era_jaを使えばいいと思う。

8
9
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?