gjtorikian / commonmarker

Ruby wrapper for the comrak (CommonMark parser) Rust crate
MIT License
429 stars 82 forks source link

Recommendations on how to have autolink for phone numbers? #139

Closed dorianmariecom closed 3 years ago

dorianmariecom commented 3 years ago

Here is how I'm doing it but it's quite hacky, the main issue is with links that contain what could be a phone number

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

  def markdown(text)
    html =
      CommonMarker.render_html(text.to_s, :HARDBREAKS, [:autolink]).html_safe
    html.gsub(PHONE_NUMBER_REGEXP) do |match|
      next match if match =~ /^[0-9]{11,}$/
      "<a href=\"sms:#{h(match)}\">#{h(match)}</a>"
    end.html_safe
  end
kivikakk commented 3 years ago

If you can use a Renderer (like HtmlRenderer), you could do this by overriding/wrapping the text callback, ensuring you don't fire on random bits of text elsewhere. The alternative would be to do this same thing as a post-processing step with Nokogiri or similar.

gjtorikian commented 3 years ago

Yeah I would say that tapping into the a elements with Nokogiri (or https://github.com/gjtorikian/html-pipeline) would be the best option here.

dorianmariecom commented 3 years ago

https://github.com/gjtorikian/html-pipeline is exactly what I need, thanks!