Syntax highlighting with CodeRay and Markdown (RDiscount) in a Rails 3 application

拟墨画扇 提交于 2019-12-04 10:15:30

In your render_body method call the coderay() method before calling the markdown() method. Using the markdown method first was generating some extra html and this confused CodeRay causing bad output.

My tests assumed you had the raw data that looked something like this in the markdown source

<code lang="ruby">
      def function(param1, param2)
        puts param1
          param2.each do |a|
            a.hello :world
          end
      end
</code>

Here's the complete class I used to test it. Note I didn't use :css => :class option because I didn't have the css to test it.

class Post < ActiveRecord::Base
  before_save :render_body

  def render_body
    self.rendered_body = markdown(coderay(self.body))
  end

  def markdown(text)
    RDiscount.new(text).to_html
  end

  def coderay(text)
    text.gsub(/\<code( lang="(.+?)")?\>(.+?)\<\/code\>/m) do
      CodeRay.scan($3, $2).div
   end
  end
end

Your final output assuming the :css => :class option should now look something like this

<div class="CodeRay"> 
  <div class="code"><pre> 
      <span class="r">def</span> <span class="fu">function</span>(param1, param2)
        puts param1
          param2.each <span class="r">do</span> |a|
            a.hello <span class="sy">:world</span> 
          <span class="r">end</span> 
      <span class="r">end</span> 
</pre></div> 
</div> 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!