require 'guard_helpers/base_helper' require "subtitle" require "ro_default" Out.out "file:#{::File.basename __FILE__} line:#{__LINE__}", "green" module ::GuardHelpers module SrtHelper include BaseHelper def start super if defined? super create_open_file("subtitle_template", "erb") cmds = ::Pry::CommandSet.new do block_command "bs", "build subtitle template in subtitle_template" do |*args| build_all_subtt end block_command "clearall", "clear all records" do |*args| Sub.delete_all Ln.delete_all end end ::Pry::Commands.import cmds end def run_on_modifications(paths) super if defined? super handle_each_path(%r{^subtitle_template/(.+)\.erb$}) do build_all_subtt end end module ClassMethods def build_all_subtt Sub.delete_all Ln.delete_all ::Find.find("subtitle_template") do |p| if test(?f, p) handle_subtitle_template(p) end end end def handle_subtitle_template(path) basename = File.basename(path).gsub(%r{\.\w+$}, "") sub = Sub.create name: basename ls = File.readlines(path).delete_if do |e| e.blank? end ls.each_with_index do |l, i| start_time, end_time, content = handle_line(l) sub.lns.create(no: i, start_time: start_time, end_time: end_time, content: content) end Sub.all.each do |sub| if sub @sub = sub filename = "lib/subtitles/#{sub.name}.srt" file = File.new(filename, "w+") subtt "srt", sub.name end end end def subtt(template, file) if $lib template_path = File.join($lib, "templates", template) + ".erb" file_path = File.join($lib, "subtitles", file) + ".srt" ctn = RoFile.read(template_path) result = ERB.new(ctn).result(binding) RoFile.write(file_path, result) format_subtitle_file(file_path) end end def format_subtitle_file(file_path) ctn = RoFile.readlines(file_path).map do |line| line.gsub(%r{^\s+}, "") end.join("\n") ::RoFile.write(file_path, ctn) end def handle_line(l) Out.out "l:#{l} file:#{File.basename __FILE__} line:#{__LINE__}", "red" if $RODEBUG r = l.match(%r{(?