Class: ShiftSubtitleCli

Inherits:
ShiftSubtitle show all
Defined in:
lib/shift_subtitle_cli.rb

Instance Method Summary collapse

Methods inherited from ShiftSubtitle

#shift_srt, #shift_timestamp

Instance Method Details

#execute(arguments) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
# File 'lib/shift_subtitle_cli.rb', line 5

def execute(arguments)
  begin
    options = parse_options arguments
    input_file = File.new options[:input_file], 'r'
    output_file = File.new options[:output_file], 'w'
    shift_srt input_file, output_file, time_to_shift(options)
  ensure
    input_file.close unless input_file.nil?
    output_file.close unless output_file.nil?
  end
end

#parse_options(arguments) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/shift_subtitle_cli.rb', line 17

def parse_options(arguments)
  options = {}
  mandatory_options = [ :operation, :seconds, :milliseconds, :input_file, :output_file ]
  parser = OptionParser.new do |opts|
    opts.banner = <<-BANNER.gsub(/^      /,'')
    Shift Subtitle Ruby Challenge
    
    Usage: #{File.basename($0)} --operation [add|sub] --time [seconds,milliseconds] input_file output_file
    
    Options are:
    BANNER
    opts.separator ""

    opts.on("-o", "--operation add|sub", [:add, :sub], "Add or Subtract time") do |operation|
      options[:operation] = operation
    end

    opts.on("-t", "--time seconds,milliseconds", "Seconds AND milliseconds to add or subtract") do |time|
      if (time =~ /\d+,\d+/)
        options[:seconds], options[:milliseconds] = time.split(/,/).map!{ |t| t.to_i }
      else
        raise OptionParser::InvalidArgument, "should be seconds,milliseconds"
      end
    end

    opts.on("-h", "--help", "Show this help message.") { puts opts; exit 0 }

    opts.parse!(arguments)
    options[:input_file], options[:output_file] = arguments[0], arguments[1]

    if mandatory_options.find { |option| options[option].nil? } 
      $stderr.puts opts; exit 1
    end
  end
  options
end

#time_to_shift(options) ⇒ Object

Converts the time and operation into a float (:sub 2,500 returns -2.5)



55
56
57
58
# File 'lib/shift_subtitle_cli.rb', line 55

def time_to_shift(options)
  shift_time = options[:seconds].to_i + options[:milliseconds].to_f/1000
  shift_time *= (options[:operation] == :sub)?-1:1
end