Class: SL::Shortener

Inherits:
Object
  • Object
show all
Defined in:
lib/searchlink/searches/shortener.rb

Class Method Summary collapse

Class Method Details

.confirm?(url, title: "Confirm URL?") ⇒ Boolean

Displays an AppleScript dialog to confirm shortening a URL.

Parameters:

  • url (String)

    The URL to confirm shortening for.

Returns:

  • (Boolean)

    True if the user confirms, false otherwise.



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/searchlink/searches/shortener.rb', line 20

def confirm?(url, title: "Confirm URL?")

  if SL::Util.popup_path
    cmd = %(osascript -e 'display dialog "#{url}" with title "#{title}" buttons {"Cancel", "Confirm", "Preview"}')

    res = `#{cmd}`.strip

    return res =~ /Confirm/ unless res =~ /Preview/

    res = `automator -i "#{url}" "#{SL::Util.popup_path}"`.strip

    return res.empty? ? false : res
  end

  res = system(%(osascript -e 'display dialog "#{url}" with title "#{title}" buttons {"Cancel", "Confirm"}'))

  res == 0
end

.shorten(url, shortener) ⇒ String

Shortens a URL using the specified shortener.

Examples:

SL::Shortener.shorten('http://example.com', :tinyurl)

Parameters:

  • url (String)

    The URL to shorten.

  • shortener (Symbol)

    The shortener to use (:tinyurl, :bitly, :isgd).

Returns:

  • (String)

    The shortened URL.

Raises:

  • (ArgumentError)

    If the shortener is unknown.



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/searchlink/searches/shortener.rb', line 49

def shorten(url, shortener)
  # Check if the URL is already shortened
  return url unless SL::URL.url?(url)

  known_shorteners = %i[tinyurl bitly isgd]
  return url unless known_shorteners.include?(shortener)

  unless NO_CONFIRM
    # Confirm shortening the URL
    res = SL::Shortener.confirm?(url, title: "Shorten URL?")

    return url unless res

    url = res if res.is_a?(String)
  end

  return url unless SL::URL.url?(url)

  # Use the shortener to shorten the URL
  case shortener
  when :tinyurl
    SL::TinyurlSearch.shorten(url)
  when :bitly
    SL::BitlySearch.shorten(url)
  when :isgd
    SL::IsgdSearch.shorten(url)
  else
    raise ArgumentError, "Unknown shortener"
  end
end