module Doing::StringURL

URL linking and formatting

Public Instance Methods

clean_unlinked_urls() click to toggle source

Clean up unlinked <urls>

# File lib/doing/string/url.rb, line 71
def clean_unlinked_urls
  gsub(/<(\w+:.*?)>/) do |match|
    m = Regexp.last_match
    if m[1] =~ /<a href/
      match
    else
      %(<a href="#{m[1]}" title="Link to #{m[1]}">[link]</a>)
    end
  end
end
replace_qualified_urls(**options) click to toggle source

Replace qualified urls

# File lib/doing/string/url.rb, line 46
def replace_qualified_urls(**options)
  fmt = options.fetch(:format, :html)
  gsub(%r{(?mi)(?x:
  (?<!["'\[(\\])
  (?<protocol>(?:http|https)://)
  (?<domain>[\w\-]+(?:\.[\w\-]+)+)
  (?<path>[\w\-.,@?^=%&;:/~+#]*[\w\-@^=%&;/~+#])?
  )}) do |_match|
    m = Regexp.last_match
    url = "#{m['domain']}#{m['path']}"
    proto = m['protocol'].nil? ? 'http://' : m['protocol']
    case fmt
    when :terminal
      TTY::Link.link_to("#{proto}#{url}", "#{proto}#{url}")
    when :html
      %(<a href="#{proto}#{url}" title="Link to #{m['domain']}">[#{url}]</a>)
    when :markdown
      "[#{url}](#{proto}#{url})"
    else
      m[0]
    end
  end
end