Class: Spidr::Rules

Inherits:
Object
  • Object
show all
Defined in:
lib/spidr/rules.rb

Overview

The Rules class represents collections of acceptance and rejection rules, which are used to filter data.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(accept: nil, reject: nil) ⇒ Rules

Creates a new Rules object.

Parameters:

  • accept (Array<String, Regexp, Proc>, nil) (defaults to: nil)

    The patterns to accept data with.

  • reject (Array<String, Regexp, Proc>, nil) (defaults to: nil)

    The patterns to reject data with.



23
24
25
26
27
28
29
# File 'lib/spidr/rules.rb', line 23

def initialize(accept: nil, reject: nil)
  @accept = []
  @reject = []

  @accept += accept if accept
  @reject += reject if reject
end

Instance Attribute Details

#acceptObject (readonly)

Accept rules



9
10
11
# File 'lib/spidr/rules.rb', line 9

def accept
  @accept
end

#rejectObject (readonly)

Reject rules



12
13
14
# File 'lib/spidr/rules.rb', line 12

def reject
  @reject
end

Instance Method Details

#accept?(data) ⇒ Boolean

Determines whether the data should be accepted or rejected.

Returns:

  • (Boolean)

    Specifies whether the given data was accepted, using the rules acceptance patterns.



38
39
40
41
42
43
44
# File 'lib/spidr/rules.rb', line 38

def accept?(data)
  unless @accept.empty?
    @accept.any? { |rule| test_data(data,rule) }
  else
    !@reject.any? { |rule| test_data(data,rule) }
  end
end

#reject?(data) ⇒ Boolean

Determines whether the data should be rejected or accepted.

Returns:

  • (Boolean)

    Specifies whether the given data was rejected, using the rules rejection patterns.



53
54
55
# File 'lib/spidr/rules.rb', line 53

def reject?(data)
  !accept?(data)
end

#test_data(data, rule) ⇒ Boolean (protected)

Tests the given data against a given pattern.

Returns:

  • (Boolean)

    Specifies whether the given data matched the pattern.



65
66
67
68
69
70
71
72
73
# File 'lib/spidr/rules.rb', line 65

def test_data(data,rule)
  if rule.kind_of?(Proc)
    rule.call(data) == true
  elsif rule.kind_of?(Regexp)
    !((data.to_s =~ rule).nil?)
  else
    data == rule
  end
end