Rack::Nokogiri Build Status Dependency Status

Rack Middleware that allows you to manipulate the nodes in your HTML response however you like.

Installation

Add this line to your application's Gemfile:

gem 'rack-nokogiri'

And then execute:

$ bundle

Or install it yourself as:

$ gem install rack-nokogiri

Usage

Adding Rack::Nokogiri to a Rails application

To wrap all <p> with class target with a div, we could do something like this:

require 'rack/nokogiri'

class Application < Rails::Application
  config.middleware.use Rack::Nokogiri, css: 'p.target' do |nodes|
    nodes.wrap '<div class="wrapper"></div>'
  end
end

If we wanted to use XPath instead of CSS selectors, we could do this instead:

require 'rack/nokogiri'

class Application < Rails::Application
  config.middleware.use Rack::Nokogiri, xpath: "//p[@class='target']" do |nodes|
    nodes.wrap '<div class="wrapper"></div>'
  end
end

Adding Rack::Nokogiri to a Sinatra application

For Sinatra we would do:

require 'sinatra'
require 'rack/nokogiri'

use Rack::Nokogiri, css: 'p.target' do |nodes|
  nodes.wrap '<div class="wrapper"></div>'
end

get('/') do
  '<p class="target">Hello World!</p>'
end

Adding Rack::Nokogiri to a Rackup application

For a Rackup app we would do:

require 'rack'
require 'rack/nokogiri'

use Rack::Nokogiri, css: 'p.target' do |nodes|
  nodes.wrap '<div class="wrapper"></div>'
end

run lambda { |env|
  [200, {'Content-Type' => 'text/html'}, ['<p class="target">Hello World!</p>']]
}

Meta

Contributors

License

Copyright (c) 2013 Daniel Perez Alvarez (unindented.org). This is free software, and may be redistributed under the terms specified in the LICENSE file.