class Swearjar

Constants

DEFAULT_SENSOR_MASK
EMOJI_REGEX

github.com/franklsf95/ruby-emoji-regex

VERSION
WORD_REGEX

Public Class Methods

default() click to toggle source
# File lib/swearjar.rb, line 12
def self.default
  from_language('en')
end
from_language(language) click to toggle source
# File lib/swearjar.rb, line 16
def self.from_language(language)
  new(File.join(File.dirname(__FILE__), 'config', "#{language}.yml"))
end
new(file = nil) click to toggle source
# File lib/swearjar.rb, line 20
def initialize(file = nil)
  @hash = {}
  @regexs = {}
  load_file(file) if file
end

Public Instance Methods

censor(string, censor_mask = DEFAULT_SENSOR_MASK) { |word| ... } click to toggle source
# File lib/swearjar.rb, line 45
def censor(string, censor_mask = DEFAULT_SENSOR_MASK)
  censored_string = string.to_s.dup
  scan(string) do |test, word, position|
    next unless test
    replacement = block_given? ? yield(word) : word.gsub(/\S/, censor_mask)
    censored_string[position, word.size] = replacement
  end
  censored_string
end
profane?(string) click to toggle source
# File lib/swearjar.rb, line 26
def profane?(string)
  string = string.to_s
  scan(string) {|test| return true if test }
  false
end
scorecard(string) click to toggle source
# File lib/swearjar.rb, line 32
def scorecard(string)
  string = string.to_s
  scorecard = {}
  scan(string) do |test|
    next unless test
    test.each do |type|
      scorecard[type] = 0 unless scorecard.key?(type)
      scorecard[type] += 1
    end
  end
  scorecard
end

Private Instance Methods

load_file(file) click to toggle source
# File lib/swearjar.rb, line 57
def load_file(file)
  data = YAML.load_file(file)

  data['regex'].each do |pattern, type|
    @regexs[Regexp.new(pattern, "i")] = type
  end if data['regex']

  data['simple'].each do |test, type|
    @hash[test] = type
  end if data['simple']

  data['emoji'].each do |unicode, type|
    char = [unicode.hex].pack("U")
    @hash[char] = type
  end if data['emoji']
end
scan(string, &block) click to toggle source
# File lib/swearjar.rb, line 74
def scan(string, &block)
  string.scan(WORD_REGEX) do |word|
    position = Regexp.last_match.offset(0)[0]
    test = @hash[word.downcase] ||
      @hash[word.downcase.sub(/s\z/,'')] ||
      @hash[word.downcase.sub(/es\z/,'')]
    block.call(test, word, position)
  end

  string.scan(EMOJI_REGEX) do |emoji_char|
    position = Regexp.last_match.offset(0)[0]
    block.call(@hash[emoji_char], emoji_char, position)
  end

  @regexs.each do |regex, type|
    string.scan(regex) do |word|
      position = Regexp.last_match.offset(0)[0]
      block.call(type, word, position)
    end
  end
end