Class: Find

Inherits:
Object
  • Object
show all
Defined in:
lib/rus/admin/find.rb

Overview

MIT LICENSE Copyright © 2022 Alex3Dev

Search for String(s) in file. If success, save line numbers in response hash.

Examples:

Simple search for strings included in file


action = Find['string', another_string'].in_file 'path_to_some_file'
pp action.result if action.result.any?

Compare if any line in a file start with wanted string


action = Find['def some_method'].in_file 'path_to_file.rb', :start_with
pp action.result if action.result.any?

Search in logfile if any line is equal ‘password’


action = Find['password'].in_file 'my_log_file.txt', :equal

if action.result.any?
  action.result.each do |param, line_number|
    puts "#{param} found on lines => #{line_number}"
  end
else
  puts "No match for #{action.params}"
end

Defined Under Namespace

Classes: Result

Constant Summary collapse

COMPARATION =
i[equal include start_with end_with].freeze

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.infoObject (readonly)

remember last search



39
40
41
# File 'lib/rus/admin/find.rb', line 39

def info
  @info
end

Class Method Details

.[](*add_params) ⇒ Object Also known as: add_params

Add strings to @params. Return self so we can chain methods



49
50
51
52
# File 'lib/rus/admin/find.rb', line 49

def [](*add_params)
  @params = params | add_params
  self
end

.in_dir(path, type = :equal) ⇒ Object

Search directory for file/directory name If found, names are saved in result hash



86
87
88
89
90
91
92
93
94
95
96
# File 'lib/rus/admin/find.rb', line 86

def in_dir(path, type = :equal)
  @found = {}
  Dir.entries(path).each do |file|
    next if ['.', '..'].include?(file)

    params.each do |string|
      process_line file, file, string, type
    end
  end
  @info = Result.new @params, path, @found
end

.in_file(filename, type = :include) ⇒ Object

Search each line in file for param If found, line numbers are saved in result hash



71
72
73
74
75
76
77
78
79
80
81
# File 'lib/rus/admin/find.rb', line 71

def in_file(filename, type = :include)
  @found = {}
  params.each do |string|
    line_no = 0
    File.readlines(filename).map do |line|
      line&.chomp!
      process_line (line_no += 1).pred, line, string, type
    end
  end
  @info = Result.new @params, filename, @found
end

.paramsObject

Array of strings that has to be searched.



43
44
45
# File 'lib/rus/admin/find.rb', line 43

def params
  @params ||= []
end

.resetObject Also known as: new

Start all over (Find.reset or Find.new)



57
58
59
# File 'lib/rus/admin/find.rb', line 57

def reset
  @params = []
end

.reset!Object

Start all over, remove last result



64
65
66
# File 'lib/rus/admin/find.rb', line 64

def reset!
  @params, @info = nil
end