【Rails6】gem jb への理解
実務で初めて触ったgem「jb」について、自分なりの解釈を書いて行きます🙌
もし不備などがあれば教えてください!
jb
公式様様はこちら↓
JSON形式のデータを簡単に作成する事が出来る整形ツール、かつ高速とのことです。
名前が短くどんなgemなのかパッと見わからなかったのですが、Jbuilder から取った名前みたいですね。
公式githubに記載ある使い方の欄に
Put a template file named *.jb in your Rails app's app/views/* directory, and render it.
*.jb という名前のテンプレート ファイルを Rails アプリの app/views/* ディレクトリに配置し、レンダリングします。
と書いてありました。
ファイルの拡張子が変わるので、書き方も新しく覚えなきゃいけないのかな?と思ったのですが、「ピュアな Ruby の文法で書ける」とあるように、特段新しい記法を覚える必要はなさそうですね。
jsonの型形式は記載しつつも、条件分岐やインスタンス変数も扱えるみたいです!
# app/views/messages/show.json.jb json = { content: format_content(@message.content), created_at: @message.created_at, updated_at: @message.updated_at, author: { name: @message.creator.name.familiar, email_address: @message.creator.email_address_with_name, url: url_for(@message.creator, format: :json) } } if current_user.admin? json[:visitors] = calculate_visitors(@message) end json[:comments] = @message.comments.map do |comment| { content: comment.content, created_at: comment.created_at } end