Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions lib/yt/models/content_detail.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ def initialize(options = {})
end

# @return [Integer] the duration of the video (in seconds).
# Returns 0 for ongoing live broadcasts and premieres, since the
# YouTube API does not report a duration until they have ended.
has_attribute :duration, default: 0 do |value|
to_seconds value
end
Expand Down Expand Up @@ -59,6 +61,8 @@ def length
# such as minutes is not part of the standard either; in this context,
# it will be interpreted as "0 minutes and 2 seconds".
def to_seconds(iso8601_duration)
return iso8601_duration.to_i unless iso8601_duration.is_a? String

match = iso8601_duration.match %r{^P(?:|(?<weeks>\d*?)W)(?:|(?<days>\d*?)D)(?:|T(?:|(?<hours>\d*?)H)(?:|(?<min>\d*?)M)(?:|(?<sec>\d*?)S))$}
weeks = (match[:weeks] || '0').to_i
days = (match[:days] || '0').to_i
Expand Down
4 changes: 4 additions & 0 deletions lib/yt/models/video.rb
Original file line number Diff line number Diff line change
Expand Up @@ -245,10 +245,14 @@ def self_declared_made_for_kids?

# @!attribute [r] duration
# @return [Integer] the duration of the video (in seconds).
# Returns 0 for ongoing live broadcasts and premieres, since the
# YouTube API does not report a duration until they have ended.
delegate :duration, to: :content_detail

# @!attribute [r] duration
# @return [String] the length of the video as an ISO 8601 time, HH:MM:SS.
# Returns "00:00:00" for ongoing live broadcasts and premieres, since
# the YouTube API does not report a duration until they have ended.
delegate :length, to: :content_detail

# @return [Boolean] whether the video is available in 3D.
Expand Down
10 changes: 10 additions & 0 deletions spec/models/content_detail_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,22 @@
let(:data) { {"duration"=>"PT51S"} }
it { expect(content_detail.duration).to eq 51 }
end

context 'given a content_detail without a duration (e.g. an upcoming premiere)' do
let(:data) { {} }
it { expect(content_detail.duration).to eq 0 }
end
end

describe '#length' do
context 'returns the duration in HH:MM:SS' do
let(:data) { {"duration"=>"PT1H18M52S"} }
it { expect(content_detail.length).to eq '01:18:52' }
end

context 'given a content_detail without a duration (e.g. an upcoming premiere)' do
let(:data) { {} }
it { expect(content_detail.length).to eq '00:00:00' }
end
end
end