Class: Swearjar

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

Defined Under Namespace

Classes: Tester

Constant Summary collapse

VERSION =
'0.1.0'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file) ⇒ Swearjar

Returns a new instance of Swearjar.



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/swearjar.rb', line 16

def initialize(file)
  data = YAML.load_file(file)

  @tester = FuzzyHash.new
  @hash = {}

  data['regex'].each do |pattern, type|
    @tester[Regexp.new(pattern)] = type
  end

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

end

Instance Attribute Details

#hashObject (readonly)

Returns the value of attribute hash.



14
15
16
# File 'lib/swearjar.rb', line 14

def hash
  @hash
end

#testerObject (readonly)

Returns the value of attribute tester.



14
15
16
# File 'lib/swearjar.rb', line 14

def tester
  @tester
end

Class Method Details

.defaultObject



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

def self.default
  from_language
end

.from_language(language = 'en') ⇒ Object



10
11
12
# File 'lib/swearjar.rb', line 10

def self.from_language(language='en')
  new(File.join(File.dirname(__FILE__), 'config', "#{language}.yml"))
end

Instance Method Details

#censor(string) ⇒ Object



52
53
54
55
56
# File 'lib/swearjar.rb', line 52

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

Returns:

  • (Boolean)


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

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

#scan(string, &block) ⇒ Object



32
33
34
35
36
37
38
39
# File 'lib/swearjar.rb', line 32

def scan(string, &block)
  string.scan(/\b[a-zA-Z-]+\b/) do |word|
    block.call(word, hash[word.downcase] || hash[word.downcase.gsub(/e?s$/,'')] )
  end
  if match = tester.match_with_result(string)
    block.call(match.last, match.first)
  end
end

#scorecard(string) ⇒ Object



46
47
48
49
50
# File 'lib/swearjar.rb', line 46

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