Skip to content

Instantly share code, notes, and snippets.

@lloeki
Created September 27, 2013 08:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lloeki/6725692 to your computer and use it in GitHub Desktop.
Save lloeki/6725692 to your computer and use it in GitHub Desktop.
Using Nokogiri::XML::Builder in lieu of stock pure ruby Builder for Rails builder templates
# config/initializers/nokogiri_builders.rb
# Using Nokogiri::XML::Builder in lieu of stock pure ruby Builder for Rails builder templates
# unrelated, but you might want this too to enable parsing
# XML params with Nokogiri
#ActiveSupport::XmlMini.backend = 'Nokogiri'
module Nokogiri
module XML
class Builder
# handle instruct! instead of emitting nonsense tag
def instruct!(tag, options = {})
case tag
when :xml
@version = options[:version]
@encoding = options[:encoding]
else
raise NotImplementedError(tag.inspect)
end
end
# redefined, to recover what instruct! gave us
def to_xml(*args)
if Nokogiri.jruby?
options = args.first.is_a?(Hash) ? args.shift : {}
unless options[:save_with]
options[:save_with] = Node::SaveOptions::AS_BUILDER
end
args.insert(0, options)
end
if @version || @encoding
# set options according to what was given previously
args[0][:version] = @version if @version
args[0][:encoding] = @encoding if @encoding
# do emit a declaration
args[0].delete(:save_with)
end
@doc.to_xml(*args)
end
end
end
end
module ActionView
module Template::Handlers
class Builder
# Default format used by Builder.
class_attribute :default_format
self.default_format = :xml
def call(template)
require_engine
code = <<-CODE
builder = Nokogiri::XML::Builder.new do |xml|
#{template.source}
end
# default to not emit a declaration (use instruct! instead)
save_options = Nokogiri::XML::Node::SaveOptions::NO_DECLARATION
# default to UTF-8, as it's Rails default encoding
options = { encoding: 'UTF-8', indent: 2, save_with: save_options }
self.output_buffer = builder.to_xml(options)
CODE
code
end
protected
def require_engine
@required ||= begin
require 'nokogiri'
true
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment