lib/filemagic.rb in ruby-filemagic-0.2.2 vs lib/filemagic.rb in ruby-filemagic-0.3.0

- old
+ new

@@ -1,11 +1,11 @@ require 'filemagic.so' class FileMagic - # Map abbreviated flag names to their values (:name => Constant). - MAGIC_FLAGS = [ + # Map flag names to their values (:name => Integer). + FLAGS_BY_SYM = [ :none, # No flags :debug, # Turn on debugging :symlink, # Follow symlinks :compress, # Check inside compressed files :devices, # Look at the contents of devices @@ -29,11 +29,13 @@ ].inject({}) { |flags, flag| const = "MAGIC_#{flag.to_s.upcase}" flags.update(flag => const_defined?(const) && const_get(const)) } - attr_reader :flags + # Map flag values to their names (Integer => :name). + FLAGS_BY_INT = FLAGS_BY_SYM.invert.update(0 => :none) + attr_writer :simplified @fm = Hash.new { |fm, flags| fm.has_key?(key = flags.to_s) ? fm[key] : fm[key] = new(*flags) } @@ -91,34 +93,35 @@ open(:mime, *flags, &block) end # Build the actual flags from the named flags passed as arguments. def build_flags(*flags) - _flags = *flags + int_flags = *flags - unless _flags.is_a?(Integer) - _flags = MAGIC_NONE + unless int_flags.is_a?(Integer) + int_flags = MAGIC_NONE flags.flatten.each { |flag| - if value = flag.is_a?(Integer) ? flag : MAGIC_FLAGS[flag.to_sym] - _flags |= value + if value = flag.is_a?(Integer) ? flag : FLAGS_BY_SYM[flag.to_sym] + int_flags |= value else - raise ArgumentError, "#{value.nil? ? 'no such flag' : 'flag not available'}: #{flag}" + err = value.nil? ? 'no such flag' : 'flag not available' + raise ArgumentError, "#{err}: #{flag}" end } end - _flags + int_flags end end # The actual processing happens in #new. def initialize(*flags) fm_initialize(*flags) - @flags = *flags + @flags = flags @closed = false end def close return if closed? @@ -130,25 +133,42 @@ # Optionally cut off additional information after mime-type. def file(file, simplified = simplified?) simplify_mime(fm_file(file), simplified) end + # Returns the flags as integer. + def int_flags + @flags.first + end + + # Returns the flags as array of symbols. + def flags + int, flags, log2 = int_flags, [], Math.log(2) + + while int > 0 + flags << FLAGS_BY_INT[flag = 2 ** Math.log(int).div(log2)] + int -= flag + end + + flags.reverse + end + # Optionally cut off additional information after mime-type. def buffer(buffer, simplified = simplified?) simplify_mime(fm_buffer(buffer), simplified) end def setflags(*flags) - previous_flags, @flags = @flags, self.class.build_flags(*flags) - fm_setflags(@flags) - - previous_flags + @flags = [self.class.build_flags(*flags)] + fm_setflags(int_flags) end + alias_method :flags=, :setflags def check(file = "\0") fm_check(file) end + alias_method :valid?, :check def compile(file) fm_compile(file) end