Module: Readlines::Filter

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

Instance Method Summary collapse

Instance Method Details

#apply_filter(line, value, query, operation, replacement = nil) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/readlines/readlines/filter.rb', line 8

def apply_filter(line, value, query, operation, replacement = nil)
  case query
  when :start
    matched = line.strip.start_with?(value.to_s)
  when :body
    matched = line.include?(value.to_s)
  when :end
    matched = line.strip.end_with?(value.to_s)
  else
    raise Readlines::Error::ArgumentError, "Invalid query type. Use :start, :body, or :end."
  end
  
  if matched
    case operation
    when :delete
      return nil
    when :replace
      raise Readlines::Error::ArgumentError, "Replacement value is required for replace operation." if replacement.nil?
  
      pattern = case query
      when :start
          /^#{Regexp.quote(value.to_s)}/
      when :body
          /#{Regexp.quote(value.to_s)}/
      when :end
          /#{Regexp.quote(value.to_s)}$/
      end
  
      return line.gsub(pattern, replacement)
    else
      raise Readlines::Error::ArgumentError, "Invalid operation type. Use :delete or :replace."
    end
  else
    line
  end
end