In projects targeted at an IT audience, the task of highlighting the syntax of the source files from time to time arises. Recently, I wanted to see how this problem is solved in Ruby.
For Ruby, there is a
CodeRay solution that allows server-side syntax highlighting for the following languages:
- Ruby
- WITH
- Delphi
- HTML
- RHTML (Rails)
- Nitro-xhtml
- CSS
- Diff
- Java
- Javascript
- Json
- Yaml
The backlight process takes place on the server side, so it does not load the client (if web technologies are used, such as Ruby On Rails), and it is also possible to develop separate utilities (for example, console) to create html files with highlighted code.
Consider a small example of working with CodeRay and write a small console application that will create a highlight for a given Ruby file.
First, install CodeRay with a simple command
gem install coderay
After that, we will write the program itself (I did not invent it myself, so I will save it, so to speak, in its original, intact form)
')
#!/usr/bin/env ruby
# courtesy: Helder
# obvio171.wordpress.com/2007/06/03/colorful-ruby-code-for-your-blog
# modified to output to stdout so can be used as a filter
# 2008-09-03 23:22
require 'rubygems'
require 'coderay'
if ARGV.length != 1
puts "Wrong number of arguments. Use: codecolor.rb <source_file>"
exit
end
rb_file = File.expand_path(ARGV[0])
print CodeRay.encode(
File.read(rb_file),
:ruby,
:html,
:line_numbers => :inline,
:hint => :info,
:css => :style,
:wrap => :div
)
Let us analyze this simple program in order: first, we include the coderay module in order to have access to the classes of interest. After that, check the number of command line arguments and extract the file name from the first argument. Next comes the most important part of our program - the use of the CodeRay.encode file, with which we pass the following arguments:
- highlighted text
- language whose syntax we highlight
- output format
- line number display style
- format of additional hints, to the highlighted code
- way to connect styles (maybe: class or: style)
- way to wrap items
And now we will ask the program we created to highlight itself. To do this, run this command
ruby codecolor.rb > test.html
After that, we will have a file test.html (which can be opened by any browser), containing the highlighted version of the program codecolor.rb.
Actually, that's all you need to know when using a code generator in Ruby. For a more detailed study of CodeRay I advise you to visit the
official site.