Module: SearchInFile

Defined in:
lib/search_in_file.rb,
lib/search_in_file/version.rb

Constant Summary collapse

VERSION =
"1.0.1"

Class Method Summary collapse

Class Method Details

.content_of(file) ⇒ Object



34
35
36
37
38
# File 'lib/search_in_file.rb', line 34

def self.content_of file
  class_name   = "#{extname( file )[1..-1].capitalize}Parser"
  parser_class = Object.const_get( class_name )
  file_content = parser_class.new.read_file( file )
end

.each_file_in(d_path) ⇒ Object



56
57
58
# File 'lib/search_in_file.rb', line 56

def self.each_file_in d_path
  Find.find( d_path ){ |f| yield( f ) if is_document?( f ) && block_given? }
end

.extname(file) ⇒ Object



60
61
62
# File 'lib/search_in_file.rb', line 60

def self.extname file
  File.extname( file )
end

.extname?(file, type) ⇒ Boolean

Returns:

  • (Boolean)


64
65
66
# File 'lib/search_in_file.rb', line 64

def self.extname? file, type
  extname( file ) == type
end

.find_all_in(d_path) ⇒ Object



50
51
52
53
54
# File 'lib/search_in_file.rb', line 50

def self.find_all_in d_path
  f_paths = []
  Find.find( d_path ){ |f| f_paths << f if is_document?( f ) }
  f_paths
end

.find_by_type_in(d_path, f_type) ⇒ Object



44
45
46
47
48
# File 'lib/search_in_file.rb', line 44

def self.find_by_type_in d_path, f_type
  f_paths = []
  Find.find( d_path ){ |f| f_paths << f if extname?( f, f_type ) }
  f_paths
end

.is_document?(f_name) ⇒ Boolean

Returns:

  • (Boolean)


68
69
70
# File 'lib/search_in_file.rb', line 68

def self.is_document? f_name
  Settings.supported_docs.include?( extname(f_name) )
end

.paragraphs_of(file) ⇒ Object



40
41
42
# File 'lib/search_in_file.rb', line 40

def self.paragraphs_of file
  content_of( file ).split(/\r/)
end

.search(path, term) ⇒ Object



13
14
15
# File 'lib/search_in_file.rb', line 13

def self.search( path, term )
  is_document?( path ) ? search_in_file( path, term ) : search_in_directory( path, term )
end

.search_in_directory(path, term) ⇒ Object



17
18
19
20
21
22
23
24
# File 'lib/search_in_file.rb', line 17

def self.search_in_directory( path, term )
  results = []
  each_file_in( path ) do |f_path| 
    f_result = search_in_file( f_path, term )
    results = results + f_result if !f_result.empty?
  end
  results
end

.search_in_file(f_path, term) ⇒ Object



26
27
28
29
30
31
32
# File 'lib/search_in_file.rb', line 26

def self.search_in_file( f_path, term )
  term_paragraphs = []
  file_paragraphs = paragraphs_of( f_path )
  # search for phrase
  file_paragraphs.each{ |p| term_paragraphs << p if p.include?(term) }
  term_paragraphs.empty? ? [] : [{file: f_path, paragraphs: term_paragraphs}]    
end