Class: Thredded::UsersProviderWithCache

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

Instance Method Summary collapse

Constructor Details

#initializeUsersProviderWithCache

Returns a new instance of UsersProviderWithCache.


15
16
17
18
# File 'lib/thredded/users_provider.rb', line 15

def initialize
  @mutex = Mutex.new
  @cache = {}
end

Instance Method Details

#call(names, scope) ⇒ Object


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

def call(names, scope)
  # This is not the same as the database lowercasing but it's OK.
  # The worst that can happen is some cache misses.
  names_with_lowercase = names.zip(names.map(&:downcase))
  cached = uncached = nil
  result = @mutex.synchronize do
    scope_cache = (@cache[scope.to_sql] ||= {})
    cached, uncached = names_with_lowercase.partition { |(_, lowercase)| scope_cache.key?(lowercase) }
    fetched = UsersProvider.call(uncached.map(&:first), scope)
    fetched.each do |user|
      scope_cache[user.send(Thredded.user_name_column).downcase] = user
    end
    cached.map { |(_, lowercase)| scope_cache[lowercase] }.concat(fetched)
  end
  result.uniq!
  result.compact!
  Rails.logger.info(
    "  [Thredded::UsersProviderWithCache] #{names.size} user names => #{result.size} users "\
      "(#{cached.size} cached, #{uncached.size} uncached)"
  )
  result
end