Class: CommentExtractor::File

Inherits:
File
  • Object
show all
Defined in:
lib/comment_extractor/file.rb

Constant Summary collapse

THRESHOLD_BINARY =
0.3

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#contentObject

Returns the value of attribute content


7
8
9
# File 'lib/comment_extractor/file.rb', line 7

def content
  @content
end

#shebangObject

Returns the value of attribute shebang


7
8
9
# File 'lib/comment_extractor/file.rb', line 7

def shebang
  @shebang
end

Class Method Details

.binary?(file_path) ⇒ Boolean

Returns:

  • (Boolean)

18
19
20
21
22
23
24
25
26
27
# File 'lib/comment_extractor/file.rb', line 18

def self.binary?(file_path)
  header = File.read(file_path, File.stat(file_path).blksize) || nil

  if header.nil? || header.empty?
    false
  else
    chars = header.chars
    (chars.grep(' '..'~').size / chars.size.to_f) <= THRESHOLD_BINARY
  end
end

.shebang(path) ⇒ Object


9
10
11
12
13
14
15
16
# File 'lib/comment_extractor/file.rb', line 9

def self.shebang(path)
  if File.extname(path).empty?
    line = File.open(path) { |f| f.gets }
    if /\A#!\s*(?<shebang_path>.+)/ =~ line
      shebang_path
    end
  end
end

Instance Method Details

#read_contentObject


29
30
31
32
33
34
35
36
37
# File 'lib/comment_extractor/file.rb', line 29

def read_content
  return if File.binary?(self.path)

  if File.shebang(self.path)
    self.gets # Remove shebang
  end

  CommentExtractor::Encoding.encode(self.read) || ''
end