Rack Middleware that provides syntax highlighting of code blocks, using the CodeRay, Pygments, Rouge or Ultraviolet gems.
Add this line to your application's Gemfile
:
gem 'rack-highlighter'
And then execute:
$ bundle
Or install it yourself as:
$ gem install rack-highlighter
require 'rack/highlighter'
require 'pygments'
class Application < Rails::Application
config.middleware.use Rack::Highlighter, :pygments
end
require 'sinatra'
require 'rack/highlighter'
require 'pygments'
use Rack::Highlighter, :pygments
get('/') do
'<pre><code class="ruby">puts "Hello world!"</code></pre>'
end
require 'rack'
require 'rack/highlighter'
require 'pygments'
use Rack::Highlighter, :pygments
run lambda { |env|
[200, {'Content-Type' => 'text/html'}, ['<pre><code class="ruby">puts "Hello world!"</code></pre>']]
}
You can choose which highlighter to use. Just require the right gem, and specify it when invoking the middleware.
require 'rack/highlighter'
require 'coderay'
use Rack::Highlighter, :coderay
require 'rack/highlighter'
require 'pygments'
use Rack::Highlighter, :pygments
require 'rack/highlighter'
require 'rouge'
use Rack::Highlighter, :rouge
require 'rack/highlighter'
require 'uv'
use Rack::Highlighter, :ultraviolet
With the default options, Rack::Highlighter
would recognize code blocks like the following:
<pre>
<code class="ruby">puts "Hello world!"</code>
</pre>
If your code is wrapped in other tags, for example:
<pre class="ruby">puts "Hello world!"</pre>
You can specify them in the elements
option:
use Rack::Highlighter, :pygments, { elements: ['pre'] }
If your block doesn't use the class
attribute to declare the language of the code, for example:
<pre>
<code data-lang="ruby">puts "Hello world!"</code>
</pre>
You can specify it in the attribute
option:
use Rack::Highlighter, :pygments, { attribute: 'data-lang' }
If your block uses a certain pattern to declare the language of the code, for example:
<pre>
<code class="language-ruby">puts "Hello world!"</code>
</pre>
You can specify a regular expression to match it in the pattern
option:
use Rack::Highlighter, :pygments, { pattern: /language-(?<lang>\w+)/ }
The regular expression must have a capture group named lang
for this to work.
You can pass additional parameters to the highlighter via the misc
option:
use Rack::Highlighter, :pygments, { misc: {linenos: 'inline'} }
- Code:
git clone git://github.com/unindented/rack-highlighter.git
- Home: https://github.com/unindented/rack-highlighter/
- Daniel Perez Alvarez (unindented@gmail.com)
Copyright (c) 2012 Daniel Perez Alvarez (unindented.org). This is free software, and may be redistributed under the terms specified in the LICENSE file.