Created
September 27, 2013 08:34
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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