Sha256: f60c9ec9574768b63486eae53b5fecf38d6ee370f52220ff00fc5a73bb61853b

Contents?: true

Size: 1.68 KB

Versions: 3

Compression:

Stored size: 1.68 KB

Contents

require 'yaml'
require 'fuzzy_hash'

class SwearJar
  @settings = {}

  def self.default
    self["default"]
  end

  def self.[](key)
    setup!
    words = @settings[key]
    if words
      new(words)
    else
      raise "No SwearJar is configured for #{key}"
    end
  end

  def self.setup!
    @settings = {}

    file = File.join(File.dirname(__FILE__), 'config', "#{language ||= "en"}.yml")
    YAML.load_file(file).each do |key, inner_config|
      scoped = {:words => {}, :phrases => FuzzyHash.new}

      # cycle through each config
      inner_config.each do |word, matches|
        if word.include?(" ")
          scoped[:phrases][Regexp.new(word, :case_insensitive => true)] = matches
        else
          scoped[:words][word] = matches
        end
      end

      @settings[key] = scoped
    end
  end

  def initialize(scoped)
    @scoped = scoped || {}
  end

  def scan(string, &block)
    # match words
    string.scan(/\b[a-zA-Z-]+\b/) do |word|
      if match = @scoped[:words][word.downcase]
        block.call(word, match)
      end
    end

    if match = @scoped[:phrases].match_with_result(string)
      block.call(match.last, match.first)
    end
  end

  def profane?(string)
    scan(string) {|word, test| return true unless test.nil?}
    return false
  end
  alias_method :match?, :profane?

  def scorecard(string)
    scorecard = {}
    scan(string) {|word, test| test.each { |type| scorecard.key?(type) ? scorecard[type] += 1 : scorecard[type] = 1} if test}
    scorecard
  end

  def censor(string)
    censored_string = string.dup
    scan(string) {|word, test| censored_string.gsub!(word, block_given? ? yield(word) : word.gsub(/\S/, '*')) if test}
    censored_string
  end

end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
zaarly-swearjar-0.2.1 lib/swearjar.rb
zaarly-swearjar-0.1.2 lib/swearjar.rb
zaarly-swearjar-0.1.1 lib/swearjar.rb