Module: YiffSpace::Concerns::UserNameMethods::ClassMethods

Defined in:
lib/yiffspace/concerns/user_name_methods.rb

Instance Method Summary collapse

Instance Method Details

#bulk_name_to_id(*arguments) ⇒ Hash{String => Integer, nil}

Returns a hash of normalized names to user IDs.

Parameters:

  • arguments (Array<String, Array<String>>)

    a list of names

Returns:

  • (Hash{String => Integer, nil})

    a hash of normalized names to user IDs



18
19
20
21
22
23
24
25
26
# File 'lib/yiffspace/concerns/user_name_methods.rb', line 18

def bulk_name_to_id(*arguments)
  names = arguments.flatten.map { |n| normalize_name(n) }
  results = names.index_with { |name| Utils::Cache.fetch("uni:#{name}") }.compact_blank
  missing = names - results.keys
  fetched = ::User.where("lower(name) IN (?)", missing).select(:id, :name).to_h { |u| [normalize_name(u.name), u.id] }
  not_found = (missing - fetched.keys).index_with { nil }
  fetched.each { |name, id| Utils::Cache.write("uni:#{name}", id, expires_in: 4.hours) }
  { **results, **fetched, **not_found }
end

#id_to_name(user_id) ⇒ Object



40
41
42
43
44
45
46
47
48
49
# File 'lib/yiffspace/concerns/user_name_methods.rb', line 40

def id_to_name(user_id)
  RequestStore[:id_name_cache] ||= {}
  return RequestStore[:id_name_cache][user_id] if RequestStore[:id_name_cache].key?(user_id)

  name = Cache.fetch("uin:#{user_id}", expires_in: 4.hours) do
    ::User.where(id: user_id).pick(:name) || YiffSpace.config.anonymous_user_name.call
  end
  RequestStore[:id_name_cache][user_id] = name
  name
end

#name_or_id_to_id(name) ⇒ Object



28
29
30
31
32
# File 'lib/yiffspace/concerns/user_name_methods.rb', line 28

def name_or_id_to_id(name)
  return name[1..].to_i if name =~ /\A!\d+\z/

  ::User.name_to_id(name)
end

#name_or_id_to_id_forced(name) ⇒ Object



34
35
36
37
38
# File 'lib/yiffspace/concerns/user_name_methods.rb', line 34

def name_or_id_to_id_forced(name)
  return name.to_i if name =~ /\A\d+\z/

  ::User.name_to_id(name)
end

#name_to_id(name) ⇒ Object



9
10
11
12
13
14
# File 'lib/yiffspace/concerns/user_name_methods.rb', line 9

def name_to_id(name)
  normalized_name = normalize_name(name)
  Cache.fetch("uni:#{normalized_name}", expires_in: 4.hours) do
    ::User.where("lower(name) = ?", normalized_name).pick(:id)
  end
end