Sha256: 772342a462e3c127ad6ec4e4bd8f020590a530c8f6cebb43237573e50f75e58e

Contents?: true

Size: 1.92 KB

Versions: 14

Compression:

Stored size: 1.92 KB

Contents

# frozen_string_literal: true

module Doing
  ##
  ## URL linking and formatting
  ##
  class ::String
    ##
    ## Turn raw urls into HTML links
    ##
    ## @param      opt   [Hash] Additional Options
    ##
    ## @option opt [Symbol] :format can be :markdown or
    ## :html (default)
    ##
    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 #link_urls
    def link_urls!(**opt)
      fmt = opt.fetch(:format, :html)
      replace link_urls(format: fmt)
    end

    # Remove <self-linked> formatting
    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
    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

    # Clean up unlinked <urls>
    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
  end
end

Version data entries

14 entries across 14 versions & 1 rubygems

Version Path
doing-2.1.40 lib/doing/string/url.rb
doing-2.1.39 lib/doing/string/url.rb
doing-2.1.38 lib/doing/string/url.rb
doing-2.1.37 lib/doing/string/url.rb
doing-2.1.36 lib/doing/string/url.rb
doing-2.1.35 lib/doing/string/url.rb
doing-2.1.34 lib/doing/string/url.rb
doing-2.1.33 lib/doing/string/url.rb
doing-2.1.32 lib/doing/string/url.rb
doing-2.1.31pre lib/doing/string/url.rb
doing-2.1.30 lib/doing/string/url.rb
doing-2.1.29 lib/doing/string/url.rb
doing-2.1.28 lib/doing/string/url.rb
doing-2.1.27 lib/doing/string/url.rb