Skip to content

Commit

Permalink
Extract Duration#seconds_to_formatted_duration
Browse files Browse the repository at this point in the history
  • Loading branch information
marcoroth committed Dec 7, 2024
1 parent cbc4d13 commit cae7065
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 15 deletions.
8 changes: 1 addition & 7 deletions app/helpers/talks_helper.rb
Original file line number Diff line number Diff line change
@@ -1,11 +1,5 @@
module TalksHelper
def seconds_to_formatted_duration(seconds)
parts = ActiveSupport::Duration.build(seconds).parts

values = [parts[:hours], parts.fetch(:minutes, 0), parts.fetch(:seconds, 0)].select(&:present?)

return "??:??" if values.any?(&:negative?)

values.map { |value| value.to_s.rjust(2, "0") }.join(":")
Duration.seconds_to_formatted_duration(seconds)
end
end
21 changes: 21 additions & 0 deletions app/lib/duration.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
class Duration
def self.seconds_to_formatted_duration(seconds)
if seconds.is_a?(Integer)
parts = ActiveSupport::Duration.build(seconds).parts
elsif seconds.is_a?(ActiveSupport::Duration)
parts = seconds.parts
else
raise "seconds (`#{seconds.inspect}`) is not an Integer or ActiveSupport::Duration"
end

values = [
parts.fetch(:hours, nil),
parts.fetch(:minutes, 0),
parts.fetch(:seconds, 0)
].compact

return "??:??" if values.any?(&:negative?)

values.map { |value| value.to_s.rjust(2, "0") }.join(":")
end
end
8 changes: 1 addition & 7 deletions app/models/static/video.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,7 @@ def duration_fs
end

def duration_to_formatted_cue(duration)
parts = [
duration.parts.fetch(:hours, nil),
duration.parts.fetch(:minutes, 0),
duration.parts.fetch(:seconds, 0)
].compact

parts.map { |x| x.to_s.rjust(2, "0") }.join(":")
Duration.seconds_to_formatted_duration(duration)
end

def duration
Expand Down
2 changes: 1 addition & 1 deletion app/models/talk.rb
Original file line number Diff line number Diff line change
Expand Up @@ -324,7 +324,7 @@ def formatted_date
end

def formatted_duration
duration.parts.values.map { |x| x.to_s.rjust(2, "0") }.join(":")
Duration.seconds_to_formatted_duration(duration)
end

def duration
Expand Down

0 comments on commit cae7065

Please sign in to comment.