LoginSignup
0
0

More than 1 year has passed since last update.

【Rails】刃物のノコギリじゃないよ、gemのNokogiriだよ

Posted at

Nokogiriとは

Nokogiriを利用すると、RubyからXML/HTMLを簡単に生成することが出来ます。
これは、ドキュメントの読み取り、書き込み、変更、およびクエリを行うための、賢明で理解しやすい API を提供します。

インストール方法

Gemfileに以下を記載し、bundle installする。

gem 'nokogiri'

使い方

app/lib/html_builder.rb
module HtmlBuilder
  def markup(tag_name = nil, options = {})
    root = Nokogiri::HTML::DocumentFragment.parse("")
    Nokogiri::HTML::Builder.with(root) do |doc|
      if tag_name
        doc.method_missing(tag_name, options) do
          yield(doc)
        end
      else
        yield(doc)
      end
    end
    root.to_html.html_safe
  end
end
def notes
  markup(:div, class: "notes") do |m|
    m.span "*", class: "mark"
    m.text "印の付いた項目は入力必須です。"
  end
end
0
0
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
0
0