Class: FileClassify

Inherits:
Object
  • Object
show all
Defined in:
lib/file_classify.rb,
lib/file_classify/version.rb

Constant Summary collapse

VERSION =
"0.0.2"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file_options = {}) ⇒ FileClassify

Returns a new instance of FileClassify.

Raises:

  • (ArgumentError)


7
8
9
10
11
12
# File 'lib/file_classify.rb', line 7

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

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

Instance Attribute Details

#contentsObject

Returns the value of attribute contents.



5
6
7
# File 'lib/file_classify.rb', line 5

def contents
  @contents
end

#pathObject

Returns the value of attribute path.



5
6
7
# File 'lib/file_classify.rb', line 5

def path
  @path
end

Instance Method Details

#ascii?Boolean

Returns:

  • (Boolean)


31
32
33
# File 'lib/file_classify.rb', line 31

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

#binary?Boolean

Returns:

  • (Boolean)


16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/file_classify.rb', line 16

def binary?
  file_path = self.path

  if self.contents
    temp = Tempfile.new('block_size_check', encoding: 'utf-8')
    temp.write(self.contents.force_encoding('utf-8'))
    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

#classifyObject



35
36
37
38
39
40
41
# File 'lib/file_classify.rb', line 35

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