Sha256: da557637d8b8be09eb210e0f5feb9c731a04dc297b7659efd7465ad9925ccba5

Contents?: true

Size: 957 Bytes

Versions: 1

Compression:

Stored size: 957 Bytes

Contents

require "file_classify/version"
require 'tempfile'

class FileClassify
  attr_accessor :contents, :path

  def initialize(file_options = {})
    raise ArgumentError if [:contents, :path].none? { |x| file_options.include?(x) }

    @contents = file_options[:contents]
    @path = file_options[:path]
  end

  # Based off the binary? method from ptools
  # https://github.com/djberg96/ptools/blob/a43e133b4ee10750c0d4a7f68ab5be92269bbb56/lib/ptools.rb#L78
  def binary?
    file_path = self.path

    if self.contents
      temp = Tempfile.new('block_size_check')
      temp.write(self.contents)
      temp.close

      file_path = temp.path
    end

    s = (File.read(file_path, File.stat(file_path).blksize) || "").split(//)
    return ((s.size - s.grep(" ".."~").size) / s.size.to_f) > 0.30
  end

  def ascii?
    self.binary? ? false : true
  end

  def classify
    if self.binary?
      return 'binary'
    else
      return 'ascii'
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
file_classify-0.0.1 lib/file_classify.rb