Tomato
Tomato

Reputation: 438

Rails double quotes always escaped

I was configuring syntax highlighting for my blog when I came across this problem. '"' is always escaped... Here is my code:

# in application_helper.rb
def coderay(content)
  defaults = {...}      

  content.gsub!(/\<pre\>\<code class=\"(.+?)\"\>(.+?)\<\/code\><\/pre\>/m) do
    CodeRay.scan($2, $1).div(defaults)
  end
end

def markdown(text)
  options = {...}    

  renderer = Redcarpet::Markdown.new(Redcarpet::Render::HTML, options)
  coderay(renderer.render(text)).html_safe
end

#in view file
...
<%= markdown @post.body %>
...

Everything works fine except that double quotes (") are always escaped. Tried many methods but none worked.

Any help would be appreciated!

Upvotes: 1

Views: 780

Answers (1)

Tomato
Tomato

Reputation: 438

Finally I used a less "elegant" way to solve this problem. Just in case someone else encounters this problem too.

I created a new method as follows:

  def unescape(content)
    content.gsub!(/(&quot;|&#39;|&amp;|&lt;|&gt;)/) do
      case $1
        when "&quot;"
          '"'
        when "&#39;"
          "'"
        when "&amp;"
          "&"
        when "&lt;"
          "<"
        when "&gt;"
          ">"
      end
    end
  end

Generally, this method just does some unescape.

Before doing CodeRay.scan($2, $1).div(defaults), I used the unescape method to unescape $2, then everything goes fine.

If someone knows a better way, please tell me.

Upvotes: 1

Related Questions