I wrote a script that I decided to refactor so I could add functionality to it as my coworkers think of it. I only saved four lines in the effort, but the main change is I removed both methods and reduced the number of called variables in favor of string interpolation/manipulation. Is there a preference for this? Is it better to declare a new variable just to use once, or is it more DRY to just make minor tweaks to the string when you need to use it? For example here is the original code:
$EMBED_HTML = ""
$BASE_URL = ""
$SAMPLE_FLV = ""
def normalize_directory(dir)
normalized = dir.gsub('\\', '/')
normalized += '/' unless normalized[-1] == '/'
end
def validate_directory(dir)
puts "Enter the full directory path of the flv files." unless dir
dir = dir || gets.chomp
dir = normalize_directory(dir)
until File.directory?(dir) && Dir.glob("#{dir}*.flv") != []
puts "That directory either doesn't exist or contains no .flv files. \nEnter the full directory path of the flv files."
dir = $stdin.gets.chomp
dir = normalize_directory(dir)
end
dir
end
def output_html_wrapper(flv_filename, output_folder)
html_filename = flv_filename.gsub(".flv", ".html")
html_body = $EMBED_HTML.gsub($SAMPLE_FLV, flv_filename.sub(/[a-z][:]/, ''))
html_output = File.open(html_filename, "w")
html_output.write(html_body)
html_output.close
link = flv_filename.sub(/[a-z][:]/, '').gsub(".flv", ".html")
link_list = File.open("#{output_folder}List of Links.txt", "a")
link_list.write($BASE_URL + link + "\n")
link_list.close
puts "#{html_filename} created successfully." if File.exists?(html_filename)
end
folder = ARGV[0].dup unless ARGV.empty?
folder = validate_directory(folder)
flvs = Dir.glob("#{folder}*.flv")
File.delete("#{folder}List of Links.txt") if File.exists?("#{folder}List of Links.txt")
flvs.each { |flv| output_html_wrapper(flv, folder) }
And the new stuff:
flash_folder = ARGV[0].dup unless ARGV.empty?
if !flash_folder
puts "Enter the full directory path of the flv files."
flash_folder = gets.chomp
end
flash_folder.gsub!('\\', '/')
flash_folder += '/' unless flash_folder[-1..-1] == '/'
until File.directory?(flash_folder) && Dir.glob("#{flash_folder}*.flv") != []
puts "That directory either doesn't exist or contains no .flv files. \nEnter the full directory path of the flv files."
flash_folder = $stdin.gets.chomp
flash_folder.gsub!('\\', '/')
flash_folder += '/' unless flash_folder[-1..-1] == '/'
end
flash_files = Dir.glob("#{flash_folder}*.flv")
File.delete("#{flash_folder}List of Links.txt") if File.exists?("#{flash_folder}List of Links.txt")
flash_files.each do |flv|
html_output = File.open("#{flv.gsub(".flv", ".html")}", "w")
html_output.write("#{embed_code.gsub("sample.flv", flv.slice(7..flv.length))}")
html_output.close
link_list = File.open("#{flash_folder}List of Links.txt", "a")
link_list.write("#{flash_url}#{flv.slice(2..flv.length).gsub(".flv", ".html")}\n")
link_list.close
end
puts "Finished."