Rack::Gsub

Description

This is a Rack middleware wrapper for gsub. You can replace text on your web page without worrying about accidentally modifying the HTML tags themselves.

Usage

This will replace all occurrences of “five” with “three” and will remove all occurrences of “the”:

use Rack::Gsub, "five" => "three", "the" => ""

This is the syntax for using within Rails’ config/environment.rb:

config.middleware.use Rack::Gsub, "five" => "three", "the" => ""

Details

You can use regular expressions, too, just like with Ruby’s gsub:

use Rack::Gsub, /five/ => "5"
use Rack::Gsub, /f\w+e/ => "5"

By default, the arguments are case-sensitive. Use the /i regex switch to do a case-insensitive replace:

use Rack::Gsub, /five/i => "5"

Only text within the body of the document is replaced. The following will only replace the word “five” in the body, not in the page’s title:

use Rack::Gsub, "five" => "5"

Rack::Gsub does not replace the text inside form elements.

Rack::Gsub eventually passes the arguments to Ruby’s String.gsub method, so it behaves the same way.

use Rack::Gsub, /five/ => "5"
# gets turned into
string.gsub(/five/, "5")