9

I would like to add a simple markdown to user comments.

When user submits this comment:

I just got [card:Black Lotus] man. POW!

I would like it to be display like this:

I just got Black Lotus man. POW!

but with extra html markup:

I just got <span class="preview" data-card="/cards/card.id">Black Lotus</span> man. POW!

1) I looked at Redcarpet but can't figure out how to add [card:...] markdown to it.

2) or should I just run regexp and replace content before saving it to DB and then sanitize(ActionView::Helpers::SanitizeHelper) span tag before displaying a comment?

user664833
  • 18,397
  • 19
  • 91
  • 140
Kocur4d
  • 6,701
  • 8
  • 35
  • 53

1 Answers1

9

Answering my own question:

Defining custom renderer and overwriting normal_text method does a job.

class HTMLwithCards < Redcarpet::Render::HTML
  def preprocess(full_document)
    full_document.gsub(/\[card:(.*)\]/) do
      card = Card.find_by_name($1)
      if card
        "<span class='preview' data-card='/cards/#{card.id}'>#{$1}</span>"
      else
        $1
      end 
    end
  end
end

and then you can call it like this:

def markdown(text)
  renderer = HTMLwithCards.new(hard_wrap: true, filter_html: true)
  Redcarpet::Markdown.new(renderer).render(text).html_safe
end
iconoclast
  • 21,213
  • 15
  • 102
  • 138
Kocur4d
  • 6,701
  • 8
  • 35
  • 53
  • AFAIK you need to use `preprocess` instead of `normal_text`, so I'm editing this. If you know something I'm missing, please correct my correction. – iconoclast Sep 05 '13 at 03:48
  • @iconoclast Won't using `preprocess` in this way require you to have `filter_html` off? I think a solution using `normal_text` or `postprocess` would be the way to go here, depending on if you care if your syntax messes up code blocks – Tapio Saarinen Nov 17 '13 at 00:33