lib/swearjar.rb in zaarly-swearjar-0.1.0 vs lib/swearjar.rb in zaarly-swearjar-0.1.1
- old
+ new
@@ -1,49 +1,67 @@
require 'yaml'
require 'fuzzy_hash'
-class Swearjar
+class SwearJar
+ @settings = {}
def self.default
- from_language
+ self["default"]
end
- def self.from_language(language='en')
- new(File.join(File.dirname(__FILE__), 'config', "#{language}.yml"))
+ def self.[](key)
+ setup!
+ words = @settings[key]
+ if words
+ new(words)
+ else
+ raise "No SwearJar is configured for #{key}"
+ end
end
- attr_reader :tester, :hash
+ def self.setup!
+ @settings = {}
- def initialize(file)
- data = YAML.load_file(file)
+ file = File.join(File.dirname(__FILE__), 'config', "#{language ||= "en"}.yml")
+ YAML.load_file(file).each do |key, inner_config|
+ scoped = {:words => {}, :phrases => FuzzyHash.new}
- @tester = FuzzyHash.new
- @hash = {}
+ # 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
- data['regex'].each do |pattern, type|
- @tester[Regexp.new(pattern)] = type
+ @settings[key] = scoped
end
+ end
- data['simple'].each do |test, type|
- @hash[test] = type
- end
-
+ def initialize(scoped)
+ @scoped = scoped || {}
end
def scan(string, &block)
+ # match words
string.scan(/\b[a-zA-Z-]+\b/) do |word|
- block.call(word, hash[word.downcase] || hash[word.downcase.gsub(/e?s$/,'')] )
+ if match = @scoped[:words][word.downcase]
+ block.call(word, match)
+ end
end
- if match = tester.match_with_result(string)
+
+ 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 if !test.nil?}
+ 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
@@ -54,5 +72,6 @@
scan(string) {|word, test| censored_string.gsub!(word, block_given? ? yield(word) : word.gsub(/\S/, '*')) if test}
censored_string
end
end
+