Commit 63ae54f7 by Janko Marohnić

Use StringIO to remove duplication

Previously we had to separate branches which did the same thing, one was
for IOs and other was for strings. However, if we wrap the string into a
StringIO, we can use the same branch for both.
parent d12011fd
require 'mimemagic/tables' require 'mimemagic/tables'
require 'mimemagic/version' require 'mimemagic/version'
require 'stringio'
# Mime type detection # Mime type detection
class MimeMagic class MimeMagic
attr_reader :type, :mediatype, :subtype attr_reader :type, :mediatype, :subtype
...@@ -113,8 +115,7 @@ class MimeMagic ...@@ -113,8 +115,7 @@ class MimeMagic
MAGIC.send(method) { |type, matches| magic_match_io(io, matches) } MAGIC.send(method) { |type, matches| magic_match_io(io, matches) }
else else
str = io.respond_to?(:read) ? io.read : io.to_s str = io.respond_to?(:read) ? io.read : io.to_s
str = str.force_encoding(Encoding::BINARY) if str.respond_to?(:force_encoding) magic_match(StringIO.new(str), method)
MAGIC.send(method) { |type, matches| magic_match_str(str, matches) }
end end
end end
...@@ -133,18 +134,5 @@ class MimeMagic ...@@ -133,18 +134,5 @@ class MimeMagic
end end
end end
def self.magic_match_str(str, matches) private_class_method :magic_match, :magic_match_io
matches.any? do |offset, value, children|
match =
if Range === offset
x = str[offset.begin, offset.end - offset.begin + value.bytesize]
x && x.include?(value)
else
str[offset, value.bytesize] == value
end
match && (!children || magic_match_str(str, children))
end
end
private_class_method :magic_match, :magic_match_io, :magic_match_str
end end
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment