Class: Deface::Matchers::Range

Inherits:
Object
  • Object
show all
Defined in:
lib/deface/matchers/range.rb

Instance Method Summary collapse

Constructor Details

#initialize(name, selector, end_selector) ⇒ Range

Returns a new instance of Range.



4
5
6
7
8
# File 'lib/deface/matchers/range.rb', line 4

def initialize(name, selector, end_selector)
  @name = name
  @selector = selector
  @end_selector = end_selector
end

Instance Method Details

#matches(document, log = true) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/deface/matchers/range.rb', line 10

def matches(document, log=true)
  starting, ending = select_endpoints(document, @selector, @end_selector)

  if starting && ending
    if log
      Rails.logger.info("\e[1;32mDeface:\e[0m '#{@name}' matched starting with '#{@selector}' and ending with '#{@end_selector}'")
    end

    return [select_range(starting, ending)]
  else
    if starting.nil?
      Rails.logger.info("\e[1;32mDeface:\e[0m '#{@name}' failed to match with starting selector '#{@selector}'")
    else
      Rails.logger.info("\e[1;32mDeface:\e[0m '#{@name}' failed to match with end selector '#{@end_selector}'")
    end
    return []
  end
end

#select_endpoints(doc, start, finish) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/deface/matchers/range.rb', line 29

def select_endpoints(doc, start, finish)
  # targeting range of elements as end_selector is present
  #
  finish = "#{start} ~ #{finish}"
  starting    = doc.css(start).first

  ending = if starting && starting.parent
    starting.parent.css(finish).first
  else
    doc.css(finish).first
  end

  return starting, ending

end

#select_range(first, last) ⇒ Object

finds all elements upto closing sibling in nokgiri document



47
48
49
# File 'lib/deface/matchers/range.rb', line 47

def select_range(first, last)
  first == last ? [first] : [first, *select_range(first.next, last)]
end