Skip to content

Instantly share code, notes, and snippets.

@sishen
Created June 10, 2011 17:49
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save sishen/1019347 to your computer and use it in GitHub Desktop.
Save sishen/1019347 to your computer and use it in GitHub Desktop.
Nokogiri Template Builder. (Rails 3.0)
require 'action_view'
module ActionView
module Template::Handlers
class NokogiriBuilder
class_attribute :default_format
self.default_format = Mime::XML
def call(template)
require 'nokogiri'
"xml = ::Nokogiri::XML::Builder.new { |xml|" +
template.source +
"}.to_xml;"
end
end
end
end
ActionView::Template.register_template_handler :nokogiri, ActionView::Template::Handlers::NokogiriBuilder.new
@OpenCoderX
Copy link

Where should I put this in my Rails app? What should the template file extension be?

@jpowell
Copy link

jpowell commented Apr 21, 2012

Placing files like this in the lib directory is sufficient. If you have many builders(handlers), then adding a lib/builders/ or lib/handlers/ directory may be better. Note that you'll need to add those paths to your application config with something like:

config.autoload_paths += Dir[ "#{config.root}/lib/**/" ]

This will add all subdirectories in lib to your application auto load path. You could just add the specific paths you want to require.

The template file extension is your choice. In this gist, NokogiriBuilder.new is registered to handle files with the extension :nokogiri

@OpenCoderX
Copy link

Are you still using this? It is not working with rails 3.2.6.

@eagleas
Copy link

eagleas commented May 10, 2017

Still working at rails 4.2.8

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment