Coderay renders actual ruby code

134 Views Asked by At

I have RedCloth with Coderay installed to highlight my code pasted in my blog.

If I paste some code like this:

 CodeRay.scan(
"set_meta_tags :og => {
        :title => @blog.title,
        :type => 'article',
        :url => current_url,
        :image => @blog.blog_images.first.image.url,
        :article => {:published_time => @blog.created_at.to_time.iso8601,
                     :modified_time => @blog.updated_at.to_time.iso8601,
                     :author => 'Name',
                     :section => @blog.categories.first.name,
                     :tags => @blog.categories.map(&:name).join(', ')
        }}",
:ruby).div(:css => :class)

I got this

set_meta_tags :og => {

        :title => blog</span>.title,
        <span class="symbol">:type</span> =&gt; <span class="string"><span class="delimiter">'</span><span class="content">article</span><span class="delimiter">'</span></span>,
        <span class="symbol">:url</span> =&gt; current_url,
        <span class="symbol">:image</span> =&gt; <span class="instance-variable">blog.blog_images.first.image.url,

        :article => {:published_time => blog</span>.created_at.to_time.iso8601,
                     <span class="symbol">:modified_time</span> =&gt; <span class="instance-variable">blog.updated_at.to_time.iso8601,

                     :author => ‘Name’,

                     :section => blog</span>.categories.first.name,
                     <span class="symbol">:tags</span> =&gt; <span class="instance-variable">blog.categories.map(&:name).join(‘, ’)

        }}

How can I get rid of that?

Many thanks

1

There are 1 best solutions below

5
On BEST ANSWER

You can pass the markup through sanitize before outputting it in the view. This will keep harmless html tags, but strip potentially harmful things such as <script>:

<%= sanitize CodeRay.scan(..., :ruby).div(:css => :class) %>

If you can trust the markup 100% (I think you can in this case), you can use raw to bypass escaping or html_safe to mark the string as safe. This will lead to all tags being outputted.

<%= raw CodeRay.scan(..., :ruby).div(:css => :class) %>

or

<%= CodeRay.scan(..., :ruby).div(:css => :class).html_safe %>

Also see http://guides.rubyonrails.org/active_support_core_extensions.html#output-safety