Module: Doing::StringURL

Included in:
String
Defined in:
lib/doing/string/url.rb

Overview

URL linking and formatting

Instance Method Summary collapse

Instance Method Details

#clean_unlinked_urlsObject

Clean up unlinked



71
72
73
74
75
76
77
78
79
80
# 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

Turn raw urls into HTML links

:html (default)

Parameters:

  • opt (Hash)

    Additional Options

Options Hash (**opt):

  • :format (Symbol)

    can be :markdown or



16
17
18
19
20
21
22
23
24
25
# File 'lib/doing/string/url.rb', line 16

def link_urls(**opt)
  fmt = opt.fetch(:format, :html)
  return self unless fmt

  str = dup

  str = str.remove_self_links if fmt == :markdown

  str.replace_qualified_urls(format: fmt).clean_unlinked_urls
end

See Also:



28
29
30
31
# File 'lib/doing/string/url.rb', line 28

def link_urls!(**opt)
  fmt = opt.fetch(:format, :html)
  replace link_urls(format: fmt)
end

Remove formatting



34
35
36
37
38
39
40
41
42
43
# File 'lib/doing/string/url.rb', line 34

def remove_self_links
  gsub(/<(.*?)>/) do |match|
    m = Regexp.last_match
    if m[1] =~ /^https?:/
      m[1]
    else
      match
    end
  end
end

#replace_qualified_urls(**options) ⇒ Object

Replace qualified urls



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# 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