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.



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

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

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

Instance Attribute Details

#acceptObject (readonly)

Accept rules



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

def accept
  @accept
end

#rejectObject (readonly)

Reject rules



14
15
16
# File 'lib/spidr/rules.rb', line 14

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.



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

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.



55
56
57
# File 'lib/spidr/rules.rb', line 55

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.



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

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