Class: Yt::Models::URL

Inherits:
Object
  • Object
show all
Defined in:
lib/yt/models/url.rb

Overview

Provides methods to identify YouTube resources from names or URLs.

Examples:

Identify a YouTube video from its short URL:

url = Yt::URL.new 'youtu.be/kawaiiguy'
url.id # => 'UC4lU5YG9QDgs0X2jdnt7cdQ'
url.resource # => #<Yt::Channel @id=UC4lU5YG9QDgs0X2jdnt7cdQ>

See Also:

Constant Summary collapse

PLAYLIST_PATTERNS =

Returns patterns matching URLs of YouTube playlists.

Returns:

  • (Array<Regexp>)

    patterns matching URLs of YouTube playlists.

[
   %r{^(?:https?://)?(?:www\.)?youtube\.com/playlist/?\?list=(?<id>[a-zA-Z0-9_-]+)},
]
VIDEO_PATTERNS =

Returns patterns matching URLs of YouTube videos.

Returns:

  • (Array<Regexp>)

    patterns matching URLs of YouTube videos.

[
  %r{^(?:https?://)?(?:www\.)?youtube\.com/watch\?v=(?<id>[a-zA-Z0-9_-]{11})},
  %r{^(?:https?://)?(?:www\.)?youtu\.be/(?<id>[a-zA-Z0-9_-]{11})},
  %r{^(?:https?://)?(?:www\.)?youtube\.com/embed/(?<id>[a-zA-Z0-9_-]{11})},
  %r{^(?:https?://)?(?:www\.)?youtube\.com/v/(?<id>[a-zA-Z0-9_-]{11})},
]
CHANNEL_PATTERNS =

Returns patterns matching URLs of YouTube channels.

Returns:

  • (Array<Regexp>)

    patterns matching URLs of YouTube channels.

[
  %r{^(?:https?://)?(?:www\.)?youtube\.com/channel/(?<id>UC[a-zA-Z0-9_-]{22})},
  %r{^(?:https?://)?(?:www\.)?youtube\.com/(?<format>c/|user/)?(?<name>[a-zA-Z0-9_-]+)}
]

Instance Method Summary collapse

Constructor Details

#initialize(text) ⇒ URL

Returns a new instance of URL.

Parameters:

  • text (String)

    the name or URL of a YouTube resource (in any form).



15
16
17
18
# File 'lib/yt/models/url.rb', line 15

def initialize(text)
  @text = text.to_s.strip
  @match = find_pattern_match
end

Instance Method Details

#id<String, nil>

Returns the ID of the YouTube resource matching the URL.

Returns:

  • (<String, nil>)

    the ID of the YouTube resource matching the URL.



27
28
29
# File 'lib/yt/models/url.rb', line 27

def id
  @match['id'] ||= fetch_id
end

#kindSymbol

Possible values are: :playlist, :video, :channel, and +:unknown:.

Returns:

  • (Symbol)

    the kind of YouTube resource matching the URL.



22
23
24
# File 'lib/yt/models/url.rb', line 22

def kind
  @match[:kind]
end

#resource(options = {}) ⇒ <Yt::Channel>

Returns the resource associated with the URL.

Returns:

  • (<Yt::Channel>)

    the resource associated with the URL



32
33
34
35
36
37
38
39
# File 'lib/yt/models/url.rb', line 32

def resource(options = {})
  @resource ||= case kind
    when :channel then Yt::Channel
    when :video then Yt::Video
    when :playlist then Yt::Playlist
    else raise Yt::Errors::NoItems
  end.new options.merge(id: id)
end