Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,12 @@ Moderate.configure do |config|

# Exclude words from the default list (false positives)
config.excluded_words = ["good"]

# Matchind text_field with blacklist regexp pattern
config.blacklist_regexp_pattern = /.*bad_pattern.*/

# Matchind text_field with whitelist regexp pattern
config.whitelist_regexp_pattern = /.*good_pattern.*/
end
```

Expand Down
8 changes: 7 additions & 1 deletion lib/moderate.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,18 @@ def configure
end

class Configuration
attr_accessor :error_message, :additional_words, :excluded_words
ACCESSORS = %i[
error_message additional_words excluded_words blacklist_regexp_pattern whitelist_regexp_pattern
].freeze

attr_accessor(*ACCESSORS)

def initialize
@error_message = "contains moderatable content (bad words)"
@additional_words = []
@excluded_words = []
@blacklist_regexp_pattern = nil
@whitelist_regexp_pattern = nil
end
end
end
23 changes: 21 additions & 2 deletions lib/moderate/text.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ class << self
def bad_words?(text)
return false if text.blank?

return true if match_blacklist_regexp_pattern?(text)
return true if not_match_whitelist_regexp_pattern?(text)

@words_set ||= Set.new(compute_word_list)
text.downcase.split(/\W+/).any? { |word| @words_set.include?(word) }
end
Expand All @@ -19,8 +22,8 @@ def compute_word_list
words
end

result = (@default_words + Moderate.configuration.additional_words -
Moderate.configuration.excluded_words).to_set
result = (@default_words + configuration.additional_words -
configuration.excluded_words).to_set
logger.debug("[moderate gem] Final word list size: #{result.size}")
result
end
Expand All @@ -33,6 +36,22 @@ def reset_word_list!
def logger
@logger ||= defined?(Rails) ? Rails.logger : Logger.new($stdout)
end

def configuration
@configuration ||= Moderate.configuration
end

def match_blacklist_regexp_pattern?(text)
pattern = configuration.blacklist_regexp_pattern

pattern.is_a?(Regexp) && pattern.match?(text)
end

def not_match_whitelist_regexp_pattern?(text)
pattern = configuration.whitelist_regexp_pattern

pattern.is_a?(Regexp) && !pattern.match?(text)
end
end
end
end
1 change: 0 additions & 1 deletion lib/moderate/text_validator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,5 @@ def validate_each(record, attribute, value)
end
end
end

end
end