Once I have a File
instance, I would like to check if it matches a file format and extend
that instance with corresponding methods:
module MP3
def self.extended(base)
raise "Can only extend a File" unless base.is_a?(File)
raise "Incorrect file format" unless is_mp3?(base)
end
def self.is_mp3?(file)
# Full metadata check if it is a MP3 format
end
def year
# Extract year from metadata
end
end
song = File.new("song.mp3")
if MP3.is_mp3?(song)
song.extend(MP3)
puts song.ctime # Original File method
puts song.year # Extended MP3 method
end
picture = File.new("picture.jpg")
MP3.is_mp3?(picture) #=> False
picture.extend(MP3) #=> raise "Incorrect file format"
I guess that is not conventional but my needs are:
- Be able to handle several file formats.
- Open a file before knowing its format.
- Re-use the same
File
instance without having to create a new object. (see below) - Have both original
File
methods and format specific methods in the same object. - Check the file format is correct before adding corresponding methods.
Is this approach correct?
This question is a follow-up of a previous question.
I want to extend the existing File
instance instead of creating a new instance because I am using a wrapper for File
, that holds the whole file in RAM (read from a tape drive that does not allow sequential access).