Chris Britt Chris Britt - 4 months ago 9
Ruby Question

CodeRay adds incorrect indentation

I am using CodeRay version 1.1.1 to render a ruby file. However, it is adding a large number of extra spaces to indent all lines except the first line.

As a MCVE, I have a file called something.rb with contents:

# This comment will not be indented
# This comment WILL be indented


In the controller I have:

contents = File.read('something.rb')
@syntax_highlighted = CodeRay.scan(contents, :ruby).div


And in the view, I have

= raw @syntax_highlighted


However, for an output I receive as seen here: Incorrect output

Answer

This is caused by HAML messing with your whitespace. See HAML's documentation on Whitespace Preservation.

Sometimes you don’t want Haml to indent all your text. For example, tags like pre and textarea are whitespace-sensitive; indenting the text makes them render wrong.

You'll need to use ~ instead of the usual = so your view would be:

~ raw @syntax_highlighted