Module: Readlines::Search

Included in:
ReadDuc
Defined in:
lib/readlines/readlines/search.rb

Instance Method Summary collapse

Instance Method Details

#search_about_now(value, show_lines: false) ⇒ Object

Raises:

  • (Readlines::NotFoundError)


7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/readlines/readlines/search.rb', line 7

def search_about_now(value, show_lines: false)
  raise Readlines::NotFoundError, "File not found: #{@file_path}" unless ::File.exist?(@file_path)

  content = ::File.read(@file_path)

  if content.include?(value)
    if show_lines
      lines = content.lines
      matched_lines = lines.each_with_index.select { |line, index| line.include?(value) }
      matched_lines.map { |(line, line_number)| line_number + 1 }
    else
      true
    end
  else
    false
  end
end

#search_in_range_now(start_line, end_line, pattern) ⇒ Object

Raises:

  • (Readlines::NotFoundError)


37
38
39
40
41
42
43
44
# File 'lib/readlines/readlines/search.rb', line 37

def search_in_range_now(start_line, end_line, pattern)
  raise Readlines::NotFoundError, "File not found: #{@file_path}" unless ::File.exist?(@file_path)

  content = ::File.readlines(@file_path)
  range = (start_line - 1)..(end_line - 1)
  matched_lines = content[range].select { |line| line.match?(pattern) }
  matched_lines
end

#search_logical_patterns_now(patterns, operator) ⇒ Object

Raises:

  • (Readlines::NotFoundError)


46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/readlines/readlines/search.rb', line 46

def search_logical_patterns_now(patterns, operator)
  raise Readlines::NotFoundError, "File not found: #{@file_path}" unless ::File.exist?(@file_path)
  raise ArgumentError, "Invalid logical operator: #{operator}" unless %w[AND OR].include?(operator)

  content = ::File.read(@file_path)
  matched_lines = content.lines.select do |line|
    case operator
    when 'AND'
      patterns.all? { |pattern| line.match?(pattern) }
    when 'OR'
      patterns.any? { |pattern| line.match?(pattern) }
    end
  end
  matched_lines
end

#search_multiple_patterns_now(patterns) ⇒ Object

Raises:

  • (Readlines::NotFoundError)


25
26
27
28
29
30
31
32
33
34
35
# File 'lib/readlines/readlines/search.rb', line 25

def search_multiple_patterns_now(patterns)
  raise Readlines::NotFoundError, "File not found: #{@file_path}" unless ::File.exist?(@file_path)

  content = ::File.read(@file_path)
  result = {}
  patterns.each do |pattern|
    count = content.scan(pattern).length
    result[pattern] = count
  end
  result
end