Skip to content

Instantly share code, notes, and snippets.

@Oshuma
Created July 11, 2010 05:21
Show Gist options
  • Save Oshuma/471308 to your computer and use it in GitHub Desktop.
Save Oshuma/471308 to your computer and use it in GitHub Desktop.
class MediaList
# File extensions.
TYPES = {
:audio => [
'aac',
'aif',
'flac',
'mp3',
'oga',
'ogg',
'wav',
'wma',
],
:video => [
'avi',
'mp4',
'mpeg',
'mov',
'ogv',
]
}
def self.show_help(error = nil)
$stderr.puts(error) if error
$stderr.puts("Usage: #{$0} <audio|video> </path/to/media>")
exit
end
def show_help(*args)
self.class.show_help(*args)
end
def initialize(args)
@type, @path = validate(args)
@files = []
end
def print
header = "#{@type} media in #{@path}:"
$stdout.puts(header)
$stdout.puts('-' * header.size)
read_files if @files.empty?
@files.each { |file| $stdout.puts(file) }
end
def read_files
Dir["#{@path}/**/*"].each do |full_path|
next if File.directory?(full_path)
extname = File.extname(full_path).gsub(/^[.]/, '')
case @type
when 'audio'
@files << name_for(full_path) if TYPES[:audio].include?(extname)
when 'video'
@files << name_for(full_path) if TYPES[:video].include?(extname)
else
raise "Unknown type: #{@type}"
end
end
end
private
def name_for(full_path)
full_path.gsub(/#{@path}\//, '')
end
def validate(args)
show_help unless args[0] && args[1]
type = validate_type(args[0])
path = validate_path(args[1])
[ type, path ]
end
def validate_type(type_name)
unless (type_name == 'audio') || (type_name == 'video')
show_help("Type must be: 'audio' or 'video'")
end
type_name.downcase
end
def validate_path(path)
full_path = File.expand_path(path)
unless File.exists?(full_path)
show_help("Directory not found: #{full_path}")
end
full_path
end
end
if $0 == __FILE__
if ARGV.size < 2
MediaList.show_help
end
MediaList.new(ARGV).print
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment