Reputation: 2202
I am using ruby-2.1 and I want to check if a file is of type video. I want a solution for common for all operating systems.
So I tried the File Object. It has a fnmatch method which only tests for extensions using regex such as *.mp4 or *.avi and so on. But this seems very inefficient.
# Get all files of directory
all_files = Dir.entries(Dir.pwd).select { |x| !File.directory? x}
mp4_f = '*.mp4'
avi_f = '*.avi'
mkv_f = '*.mkv'
flv_f = '*.flv'
# Loop through each file
all_files.each do |file|
puts File.fnmatch(mp4_f, file) || File.fnmatch(avi_f, file) || File.fnmatch(mkv_f, file) || File.fnmatch(flv_f, file)
end
But this code seems very bad for multitudes of video types. So any solutions, would be appreciated including any gem support. Thanks.
Upvotes: 5
Views: 1236
Reputation: 1700
You could do something like this without using the ffmpeg library,
vid_formats = %w[.avi .flv .mkv .mov .mp4] #add more extensions if anything is left
all_files.each do |file|
puts vid_formats.include? File.extname(file)
end
Of course you have to maintain an array for the extension but this looks better in terms of code readability. Hope that helps
Upvotes: 2
Reputation: 84443
One cross-platform way to do this without external dependencies like libmagic is to use Dir#glob to match filename extensions. For example:
extensions = %w[avi flv mkv mov mp4]
video_files = extensions.flat_map { |ext| Dir.glob "*#{ext}" }
You can then pass the video_files Array around as needed within your program.
Upvotes: 2