Module: Sensitive
- Defined in:
- lib/sensitive.rb,
lib/sensitive/version.rb
Defined Under Namespace
Classes: Error
Constant Summary collapse
- VERSION =
"1.0.2"
Class Attribute Summary collapse
-
.words ⇒ Object
attr_accessor defines reader methods for an instance.
Class Method Summary collapse
-
.add_word(word) ⇒ Object
添加单个敏感词.
-
.empty! ⇒ Object
清空整个敏感词hash.
-
.filter(word) ⇒ Object
过滤敏感词.
-
.load_default ⇒ Object
导入Gem自带敏感词.
-
.load_file(file_path) ⇒ Object
从用户文件中导入敏感词.
Class Attribute Details
.words ⇒ Object
attr_accessor defines reader methods for an instance.
12 13 14 |
# File 'lib/sensitive.rb', line 12 def words @words end |
Class Method Details
.add_word(word) ⇒ Object
添加单个敏感词
15 16 17 18 19 20 21 22 23 |
# File 'lib/sensitive.rb', line 15 def add_word(word) word = word.strip.gsub(%r{[^\p{Han}+/ua-zA-Z0-9]}, '') word.chars.inject(self.words) do |words, char| if !words.key? char words[char] = {} end words[char] end end |
.empty! ⇒ Object
清空整个敏感词hash
26 27 28 |
# File 'lib/sensitive.rb', line 26 def empty! self.words = {} end |
.filter(word) ⇒ Object
过滤敏感词
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
# File 'lib/sensitive.rb', line 43 def filter(word) sensitive_word = '' word = word.strip.gsub(%r{[^\p{Han}+/ua-zA-Z0-9]}, '') word.chars.each_with_index.inject(self.words) do |words, (char, index)| if words.key?(char) sensitive_word += char break if words[char].empty? # 如果被检测的词已是最后一个,但关键字还不是最后,则返为空 return '' if index == word.size - 1 words[char] else # 如果上一步在关键字中,这次又不在关键字中,需要重新初始化检测 if !sensitive_word.empty? sensitive_word = '' words = self.words and redo else words end end end sensitive_word end |
.load_default ⇒ Object
导入Gem自带敏感词
38 39 40 |
# File 'lib/sensitive.rb', line 38 def load_default load_file(File.join( File.dirname(__FILE__), '../sensitives.txt' )) end |
.load_file(file_path) ⇒ Object
从用户文件中导入敏感词
31 32 33 34 35 |
# File 'lib/sensitive.rb', line 31 def load_file(file_path) File.open(file_path, 'r').each_line do |line| add_word(line) end end |