Class: SwearJar

Inherits:
Object
  • Object
show all
Defined in:
lib/swearjar.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(scoped) ⇒ SwearJar

Returns a new instance of SwearJar.



41
42
43
# File 'lib/swearjar.rb', line 41

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

Class Method Details

.[](key) ⇒ Object



11
12
13
14
15
16
17
18
19
# File 'lib/swearjar.rb', line 11

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

.defaultObject



7
8
9
# File 'lib/swearjar.rb', line 7

def self.default
  self["default"]
end

.setup!Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/swearjar.rb', line 21

def self.setup!
  return unless @settings.empty?

  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

Instance Method Details

#censor(string) ⇒ Object



70
71
72
73
74
# File 'lib/swearjar.rb', line 70

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

#profane?(string) ⇒ Boolean Also known as: match?

Returns:

  • (Boolean)


58
59
60
61
# File 'lib/swearjar.rb', line 58

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

#scan(string, &block) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/swearjar.rb', line 45

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

#scorecard(string) ⇒ Object



64
65
66
67
68
# File 'lib/swearjar.rb', line 64

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