Class: Redactor

Inherits:
Object
  • Object
show all
Defined in:
lib/redactor.rb,
lib/redactor/dsl.rb,
lib/redactor/rule.rb,
lib/redactor/extract.rb,
lib/redactor/version.rb

Defined Under Namespace

Classes: DSL, Extract, Rule

Constant Summary collapse

DEFAULT_REPLACEMENT =
'[REDACTED]'.freeze
VERSION =
'0.2.1'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(rules = [], &block) ⇒ Redactor

Returns a new instance of Redactor.



6
7
8
9
10
11
# File 'lib/redactor.rb', line 6

def initialize(rules = [], &block)
  @default_replacement = DEFAULT_REPLACEMENT
  @rules = Array(rules)

  DSL.run(self, block) if block_given?
end

Instance Attribute Details

#default_replacementObject

Returns the value of attribute default_replacement.



4
5
6
# File 'lib/redactor.rb', line 4

def default_replacement
  @default_replacement
end

#rulesObject

Returns the value of attribute rules.



4
5
6
# File 'lib/redactor.rb', line 4

def rules
  @rules
end

Instance Method Details

#extract(from) ⇒ Object

returns a list of Extract objects (including position and value) matching predefined rules



19
20
21
22
23
24
25
26
27
# File 'lib/redactor.rb', line 19

def extract(from)
  rules.reduce([]) do |extracts, rule|
    new_extracts = rule.extract(from).select do |extract|
      # do not consider new extract if colliding with existing one
      !extracts.any? { |e| e.collides?(extract) }
    end
    extracts.concat(new_extracts)
  end
end

#format(text, &block) ⇒ Object

replaces parts of text by [REDACTED]. The replacement string can be customized by passing a block taking the Extract object as an argument



31
32
33
34
35
36
# File 'lib/redactor.rb', line 31

def format(text, &block)
  extract(text).each_with_object(text.clone) do |extract, redacted_text|
    sub = block_given? ? block.call(extract) : default_replacement
    redacted_text[extract.start..extract.finish] = sub
  end
end

#register_rule(rule) ⇒ Object



13
14
15
# File 'lib/redactor.rb', line 13

def register_rule(rule)
  rules.push(rule)
end