Class: ThatLanguage::LookupContext

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(lookup_hash) ⇒ LookupContext

Returns a new instance of LookupContext.



3
4
5
# File 'lib/that_language/lookup_context.rb', line 3

def initialize(lookup_hash)
  @lookup_hash = lookup_hash
end

Class Method Details

.from_wordlist_path(wordlist_path) ⇒ Object



8
9
10
11
12
13
14
15
16
# File 'lib/that_language/lookup_context.rb', line 8

def from_wordlist_path(wordlist_path)
  if File.file?(wordlist_path)
    from_file(wordlist_path)
  elsif File.directory?(wordlist_path)
    from_directory(wordlist_path)
  else
    raise ArgumentError # TODO: spec
  end
end

Instance Method Details

#[](word) ⇒ Object

TODO: We could add memoization, but this will increase memory usage a lot



60
61
62
63
64
65
66
# File 'lib/that_language/lookup_context.rb', line 60

def [](word)
  h = {}
  language_codes.each do |language_code|
    h[language_code] = lookup_hash[language_code][word] || DEFAULT_VALUE
  end
  h
end

#language_codesObject



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

def language_codes
  @language_codes ||= lookup_hash[:language_codes].sort
end

#merge(other_lookup_context) ⇒ Object

NOTE: This code is ugly. Refactor me :(



69
70
71
72
73
74
75
76
77
78
79
# File 'lib/that_language/lookup_context.rb', line 69

def merge(other_lookup_context)
  new_lookup_hash = lookup_hash.dup
  new_lookup_hash[:language_codes] |= other_lookup_context.language_codes

  other_lookup_context.language_codes.each do |language_code|
    new_lookup_hash[language_code] ||= {}
    new_lookup_hash[language_code].merge!(other_lookup_context.lookup_hash[language_code])
  end

  LookupContext.new(new_lookup_hash)
end

#normalized(word) ⇒ Object

TODO: This code is ugly. Refactor me :(



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

def normalized(word)
  h = self[word]
  max = h.values.max

  return h if max == 0.0

  h.each do |word, value|
    h[word] = value / max
  end

  h
end