Class: WebGrep::Grep

Inherits:
Object
  • Object
show all
Defined in:
lib/web_grep/grep.rb

Instance Method Summary collapse

Constructor Details

#initialize(word:, url:, file:) ⇒ Grep

Returns a new instance of Grep.



6
7
8
9
10
11
12
13
14
# File 'lib/web_grep/grep.rb', line 6

def initialize(word:,url:,file:)
  if file && url
    raise 'Should set one of params, url or file!'
  end
  if url && !url.match('http://|https://')
    url = "http://#{url}"
  end
  @word, @url, @file = word, url, file
end

Instance Method Details

#grep!Object



16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/web_grep/grep.rb', line 16

def grep!
  Nokogiri::XML(open(@url || @file)).search('[text()*=""]').select do |e|
    e.content
      .encode('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '')
      .match /#{@word}/
  end.map do |l|
    "#{"\033[32;1m"}XPath: #{l.path}#{"\033[0m"}\n" \
    "\tMatched content: #{l.content}"
  end
rescue SocketError
  raise 'Bad url or connection!'
end