Class: Subrip::Shift

Inherits:
Object
  • Object
show all
Defined in:
lib/shift.rb

Instance Method Summary collapse

Constructor Details

#initialize(opts) ⇒ Shift

attr_reader :ip_file, :op_file, :time_to_shift, :operation



5
6
7
8
9
10
# File 'lib/shift.rb', line 5

def initialize(opts)
  @ip_file, @op_file = opts.ip_file, opts.op_file
  sec, milli_sec = *opts.time_to_shift.split(',').map(&:to_i)
  @time_to_shift = get_time_in_sec(sec, milli_sec)
  @operation = (opts.operation == :add) ? :+ : :-
end

Instance Method Details

#get_time_in_sec(sec, milli_sec) ⇒ Object



41
42
43
# File 'lib/shift.rb', line 41

def get_time_in_sec(sec, milli_sec)
  Time.at(sec, milli_sec * 1_000).to_f
end

#shift_subtitleObject



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/shift.rb', line 12

def shift_subtitle
  op_lines = File.readlines(@ip_file).map do |line|
    begin
      if line.match /(.*) --> (.*)/
        "#{transform_time($1)} --> #{transform_time($2)}\n"
      else
        # in some files newline is interpretted as carriage return
        line.chomp! + "\n"
      end
    rescue ArgumentError
      # skipping non utf-8 chars
      next
    end
  end
  File.open(@op_file, 'w') do |f|
    f << op_lines.join
  end
end

#transform_time(time, operation = @operation, time_to_shift = @time_to_shift) ⇒ Object



31
32
33
34
35
36
37
38
39
# File 'lib/shift.rb', line 31

def transform_time(time, operation=@operation, time_to_shift=@time_to_shift)
  # eg: "01:32:04,283"
  time.match /(\d+):(\d+):(\d+),(\d+)/
  hour, min = $1.to_i, $2.to_i
  sec = get_time_in_sec($3.to_i, $4.to_i)
  from_time = Time.new(Time.now.year, nil, nil, hour, min, sec) 
  to_time = from_time.send(operation, time_to_shift)
  to_time.strftime "%H:%M:%S,%3N"
end