Quantcast
Channel: Active questions tagged ruby - Stack Overflow
Viewing all articles
Browse latest Browse all 4623

How can I syntax highlight in rich text in rails

$
0
0

I am creating my first non hand held rails app. one of the features involves writing code inside of a rich text area. To highlight this code(syntax) I defaulted to making use of rouge. When I used it with just a basic form.text_field it worked well then I thought of making use of rich text (is this a good decision too?). When I made this change I updated my code_syntax highlighter in the following manner:

  def code_syntax_highlighter(content, language)    code_content = content.is_a?(ActionText::RichText) ? content.body.to_s : content    formatter = Rouge::Formatters::HTML.new    lexer = Rouge::Lexer.find(language) || Rouge::Lexers::PlainText    formatter.format(lexer.lex(code_content)).html_safe  end

Now my issue is that what comes now is a code that is wrapped in a div inside of a trix class. I am new to using this in rails and I am failing to get where I am not doing it correctly to make it work. Here is what my output looks like:

<div class="trix-content"><div>class ArticlesController &lt; ApplicationController<br>&nbsp; def create<br>&nbsp; &nbsp; article = Article.create! params.require(:article).permit(:title, :content)<br>&nbsp; &nbsp; redirect_to article<br>&nbsp; end<br>end<br><br></div></div>

Do i just make use of the text_field? or I make use of rich text and there is a solution to doing it right? (this is a shot at making something that can scale-in principle and design).

To solve this I have tried to change my helper method to :

  def code_syntax_highlighter(content, language)    code_content = content.is_a?(ActionText::RichText) ? content.body.to_s : content    formatter = Rouge::Formatters::HTML.new    lexer = Rouge::Lexer.find(language) || Rouge::Lexers::PlainText    formatter.format(lexer.lex(code_content)).html_safe  end

Viewing all articles
Browse latest Browse all 4623

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>