Module: WordCensored

Defined in:
lib/word_censored.rb,
lib/word_censored/version.rb

Defined Under Namespace

Classes: Error

Constant Summary collapse

REGEX_FIRST_LETTER =

Your code goes here…

/[a-zàáãạảăắằẳẵặâấầẩẫậèéẹẻẽêềếểễệđìíĩỉịòóõọỏôốồổỗộơớờởỡợùúũụủưứừửữựỳỵỷỹý]/i
REGEX_PREPROCESS =
/([^0-9a-zàáãạảăắằẳẵặâấầẩẫậèéẹẻẽêềếểễệđìíĩỉịòóõọỏôốồổỗộơớờởỡợùúũụủưứừửữựỳỵỷỹý ])/i
VERSION =
"0.1.7"

Instance Method Summary collapse

Instance Method Details

#combine_blacklistObject



47
48
49
50
51
52
53
# File 'lib/word_censored.rb', line 47

def combine_blacklist
  blacklist  = JSON.parse(File.read(File.join(File.dirname(__FILE__), 'files/blacklist.json')))
  eblacklist = validate_external_blacklist
  return blacklist unless eblacklist

  blacklist.merge(eblacklist) { |key, _| (blacklist[key] + eblacklist[key]).uniq }
end

#detect_badword(arr, origin_index, index, result_index = -1)) ⇒ Object



28
29
30
31
32
33
34
35
36
37
# File 'lib/word_censored.rb', line 28

def detect_badword(arr, origin_index, index, result_index = -1)
  return result_index if arr.nil?

  word           = preprocess(@str_array[origin_index..index].join(' '))
  list_badwords  = arr.find_all { |value| value =~ /\A#{word} /i }
  result_index   = index if arr.include?(word)
  return result_index if list_badwords.empty? || @str_array[index + 1].nil?

  detect_badword(list_badwords, origin_index, index + 1, result_index)
end

#filter(str) ⇒ Object



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

def filter(str)
  blacklist  = JSON.parse(File.read(File.join(File.dirname(__FILE__), 'files/blacklist.json')))
  @str_array = str.split(/[[:space:]]/)
  cindex     = -1

  @str_array.each_with_index do |word, index|
    next if index <= cindex
    next if preprocess(word).strip.empty?

    first_letter = preprocess(word)[0].match?(REGEX_FIRST_LETTER) ? preprocess(word)[0] : 'other'
    ibadword     = detect_badword(blacklist[first_letter], index, index)
    replace_asterisk(index, ibadword) && cindex = ibadword if ibadword >= index
  end

  @str_array.join(' ')
end

#preprocess(word) ⇒ Object



43
44
45
# File 'lib/word_censored.rb', line 43

def preprocess(word)
  word.downcase.gsub(REGEX_PREPROCESS, '')
end

#replace_asterisk(from, to) ⇒ Object



39
40
41
# File 'lib/word_censored.rb', line 39

def replace_asterisk(from, to)
  (from..to).to_a.each { |i| @str_array[i] = '*' * @str_array[i].length }
end

#validate_external_blacklistObject



55
56
57
58
59
60
61
62
63
64
65
# File 'lib/word_censored.rb', line 55

def validate_external_blacklist
  path = Rails.public_path.join('assets', 'blacklist.json')
  return false unless File.exist?(path)

  external = JSON.parse(File.read(path))
  return false if external.values.any? { |value| value.is_a?(String) }

  external
rescue JSON::ParserError
  false
end