LoginSignup
2
2

More than 5 years have passed since last update.

html のトルツメ

Posted at

たとえばこういうテーブルがあるとしましょうよ。

項目 内容
都道府県 東京都
市町村 北区
郵便番号 11x-xxxx
モバイル example@trick-with.net
PC hogehoge@trick-with.net
大久保
康平

でね、あるデータでは、PCアドレスが無かったり、市町村が未入力だったりするとします。そういうときは、空の枠を残さずに、以下のようにしたい、としましょう。(俗に言うトルツメ)

項目 内容
都道府県 東京都
郵便番号 11x-xxxx
モバイル example@trick-with.net
大久保
康平

別のある人は、住所を教えてくれなくて、かろうじてモバイルアドレスだけ教えてくれたので、こんな感じに表示したい、としましょう。

項目 内容
モバイル example@trick-with.net
大久保
康平

で、もし何も入力されない場合には、テーブルごとトルツメしたいわけです。

というようなことを Rails で綺麗に実現できまいか、と考えたのがこれ。

ruby
module ApplicationHelper
  def omittable(&block)
    omittable = Omittable.new
    ret = capture(omittable, &block)
    omittable.compact.empty? ? nil : ret.html_safe
  end
end

class Omittable < Array
  def <<(val)
    super
    val
  end
end

使い方はこんなん。
b は Array で、b に nil 以外の何かがあれば omittable ブロック全体を表示、
b.compact.empty? なら、omittable ブロック全体が nil を返す。

= ommitable do |b|
  %table
    %tr
      %th 小分類
      %th 内容
    =b<< ommitable do |b|
      %tr
        %th 都道府県
        %td=b<< user.prefecture
    =b<< ommitable do |b|
      %tr
        %th 市町村
        %td=b<< user.city
    =b<< ommitable do |b|
      %tr
        %th 郵便番号
        %td=b<< user.zip_code
    =b<< ommitable do |b|
      %tr
        %th モバイル
        %td=b<< user.email_mobile
    =b<< ommitable do |b|
      %tr
        %th PC
        %td=b<< user.email_pc
    =b<< ommitable do |b|
      %tr
        %th%td=b<< user.family_name
    =b<< ommitable do |b|
      %tr
        %th%td=b<< user.given_name

"" を無視したい場合は、b<< hoge.presence とすればOK.

もっと綺麗な実装法ありますかね。

2
2
0

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
2
2