Class: MediaOrganizer::Renamer

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

Overview

Renamer: primary class to use for renaming files. Allows renaming of a given list of files to a user-defined scheme based on each file’s metadata.

Key Methods

  • setNamingScheme()

  • generateRenameList()

  • overwrite()

Example Usage

old_uris = [‘./test/data/hs-2003-24-a-full_tif.tif’] scheme = [“Test-”, :date_time]

r = Renamer.new()

r.setNamingScheme(scheme)

new_uris = r.generateRenameList(old_uris)

r.overwrite(new_uris) #new filename: “./test/data/Test-2003-09-03 12_52_43 -0400.tif”)

Defined Under Namespace

Classes: FileNotFoundError, FileNotValidError, InvalidArgumentError, RenameFailedError, UnsupportedFileTypeError

Constant Summary collapse

DISALLOWED_CHARACTERS =

Characters that are not allowed in file names by many file systems. Replaced with @subchar character.

/[\\:\?\*<>\|"\/]/

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args = {}) ⇒ Renamer

Returns a new instance of Renamer.



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

def initialize(args = {})
	@naming_scheme = ["Renamed-default-"]
	@subchar = "_"
end

Instance Attribute Details

#naming_schemeObject

Array of strings and literals used to construct filenames. Set thruough setNamingScheme as opposed to typical/default accessor.



38
39
40
# File 'lib/renamer.rb', line 38

def naming_scheme
  @naming_scheme
end

#subcharObject

Character with which to substitute disallowed characters



39
40
41
# File 'lib/renamer.rb', line 39

def subchar
  @subchar
end

Instance Method Details

#generateRenameList(uri_list = [], args = {}) ⇒ Hash

Renamer.generateRenameList(): Creates a hash mapping the original filenames to the new (renamed) filenames

Hash of “file name pairs.” old_file => new_file

Parameters:

  • uri_list (Array<String>) (defaults to: [])

    contains list of URIs (as full AKA absolute paths)

  • args (Hash) (defaults to: {})

    hash of options.

Options Hash (args):

  • :scheme (Array<String, Symbol>)
    • array of strings and symbols specifying file naming convention

Returns:

  • (Hash)

    filename_pairs - mapping between old filenames and new filenames



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/renamer.rb', line 67

def generateRenameList(uri_list = [], args = {})
	if args[:scheme] != nil && args[:scheme].is_a?(Array) && !args[:scheme].empty?
		scheme = setScheme(args[:scheme])
	else
		scheme = @naming_scheme
	end
	unless !uri_list.nil? && uri_list.is_a?(Array) 
		raise InvalidArgumentError
	end

	filename_pairs = {}
	uri_list.each do |i|
		new_string = handleFile(i, scheme)
		#If this is a valid file path, add it to the filename_pairs
		#puts "New file rename added: #{new_string}"
		if new_string != nil && new_string != ""
			filename_pairs[i] = new_string
		end
	end

	return filename_pairs

rescue InvalidArgumentError => arg_e
	puts arg_e
	puts "Invalid arguments provided. Expected: uri_list = [], args = {}"
	puts arg_e.backtrace.inspect
rescue => e
	puts e 
	puts e.message 
	puts e.backtrace.inspect
end

#getFileMetadata(file) ⇒ Object

Routes metadata scrape based on file type (currently relies on extension - future version should use MIME) currently assumes file was checked for validity in calling code.

Inputs

String containing full file URI (path and filename)

Outputs

Returns hash of metadata for file, or nil if none/error.



136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/renamer.rb', line 136

def	(file)
	
	#LOAD EXIF DATA	
	case File.extname(file).downcase
	when '.jpg'
		Image::getJpegData(file)
	when '.tif'
		Image::getTiffData(file)
	when '.mp3' , '.wav' , '.flac' , '.aiff', '.ogg', '.m4a', '.asf'
		Music::getMusicData(file)
	else
		raise UnsupportedFileTypeError, "Error processing #{file}"
	end
rescue UnsupportedFileTypeError => e
	puts "Could not process file: Extension #{File.extname(file)} is not supported."
	puts e.backtrace.inspect
end

#overwrite(renames_hash = {}) ⇒ Object

Renamer.overwrite(): Writes new file names based upon mapping provided in hash argument. NOTE: this will create changes to file names!

Inputs

1. Hash containing mappings between old filenames (full URI) and new filenames (full URI). Example: => “/path/to/newfile.jpg”

Outputs

none (file names are overwritten)



106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/renamer.rb', line 106

def overwrite(renames_hash = {})
	renames_hash.each do |old_name, new_name|
		begin
			#error/integrity checking on old_name and new_name
  			raise FileNotValidError, "Could not access specified source file: #{i}." unless old_name.is_a?(String) && File.exists?(old_name)    
    		raise FileNotValidError, "New file name provided is not a string" unless new_name.is_a?(String)
    		
    		#puts (File.dirname(File.absolute_path(old_name)) + "/" + new_name) #Comment this line out unless testing
    		File.rename(File.absolute_path(old_name),File.dirname(File.absolute_path(old_name)) + "/" + new_name)
							
			#check that renamed file exists - Commented out because this currently does not work.
			#unless new_name.is_a?(String) && File.exists?(new_name)    
      		#	raise RenameFailedError, "Could not successfuly rename file: #{old_name} => #{new_name}. Invalid URI or file does not exist."
    		#end
    	rescue => e
    		puts "Ignoring rename for #{old_name} => #{new_name}"
    		puts e
    		puts e.backtrace.inspect
		end
	end
end

#setNamingScheme(arr = []) ⇒ void

This method returns an undefined value.

Renamer.setNamingScheme(): sets the naming scheme for the generateRenameList method.

Examples:

Set the naming scheme to a format like “Vacation_Photos_2014_05_22.png” based on the file’s date_taken metadata field.

setNamingScheme(["Vacation_Photos_", :date_taken]). 

Parameters:

  • arr (Array<String, Symbol>) (defaults to: [])

    contains strings and symbols representing the naming scheme.



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

def setNamingScheme(arr = [])
	@naming_scheme = setScheme(arr)
end