How to add code

highlighting to Ruby on Rails

Hash tags: Ruby on Rails Code Highlighting Action Text Trix WYSIWYG Rich Text

For some reason, very obvious tools lie somewhere really far from me and my google search engine logic :). What I mean by that is that sometimes when I really need a tool which I am pretty sure was already developed like 1000 times is hard to find. It took me a lot of time to actually find a good fit and simple solution for my blog to highlight my code quotes. Here is a demo shows how it will look:
case search_phrase
when 'all'
  photos = Photo.order("created_at DESC")
when 'new'
  photos = Photo.order("created_at DESC")
when 'old'
  photos = Photo.order("created_at ASC")
when nil
  photos = Photo.order("created_at DESC")
  photos = Photo.joins(:photo_sections).where(photo_sections:{ name: "#{search_phrase}" })
Looks good to me, and way more readable then without any highlighting. So let go straight to HOW TO!

What you need:
1. Ruby on Rails and ActionText implemented and ready to highlight.
2. highlight.js Yes that's simple and I couldn't find it for loooong time.

As you probably already saw it is very simple and easy to use. There are several ways you can add it to your application. All instructions are here. To save time and keep it as simple as possible I will be using CDNs.

First, let's choose a highlighting style on the main page by clicking the style button.
Styling your Code

When you you pick one save the style name we will need it for modifying the CDN link. In my case, I liked railscast style. So all we need to do is modify the ending of the css string to the style name like so:
<link rel="stylesheet"

Second, adding the script CDN. Make sure that you copying a correct library version. As it, for today the latest version is 9.18. Of course, this solution is for development and designing purposes only. In real env, I recommend download js and css files into your web application or use package managers like npm.
<script src="//"></script>

The last thing we need to do is adjust the js script to reflect Trix code wrapping. So usually when you create a code the WYSIWYG editor will create something like this:
<pre><code class="html">...</code></pre>
but Trix is actually doing it without code tag. We can easily fix it with a custom script. Add the following to the page where the Trix editor will be rendered:
    document.addEventListener('DOMContentLoaded', (event) => {
        document.querySelectorAll('pre').forEach((block) => {
Again, keep in mind this should not be left in the view level. I did it only for tutorial purposes the good code practice is up to you to follow.

That's it! You can always add some personal changes to styling as I did - I love when code lines are close to each other, so I reduced the line spacing from 1 to 0.8, which makes my code look more blocky like.
Photo by Min An from Pexels