Render tel: links with CommonMarker

114 Views Asked by At

I have this helper:

  def markdown(text)
    CommonMarker.render_html(text.to_s, :HARDBREAKS, [:autolink]).html_safe
  end

But I would like phone numbers like +33 7 87 12 10 21 to render tel: links.

I got the regexp figured out:

PHONE_NUMBER_REGEXP = /\+?[ 0-9()-]+[0-9)]/

But I can't find how to integrate with CommonMarker https://github.com/gjtorikian/commonmarker

Seems like I need to create a custom renderer https://github.com/gjtorikian/commonmarker#creating-a-custom-renderer

I've also tried:

text.gsub(PHONE_NUMBER_REGEXP) { |match| "[#{match}](tel:#{match})" }

to no success

1

There are 1 best solutions below

0
Dorian On

gave up trying to extend CommonMarker and just gsub-ed the html output, works well and is safe thanks to the escaping:

module ApplicationHelper
  PHONE_NUMBER_REGEXP = /\+?[ 0-9()-]{9,}[0-9)]/

  def markdown(text)
    html = CommonMarker.render_html(text.to_s, :HARDBREAKS, [:autolink]).html_safe
    html.gsub(PHONE_NUMBER_REGEXP) do |match|
      "<a href=\"tel:#{h(match)}\">#{h(match)}</a>"
    end.html_safe
  end