You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
1.3 KiB

  1. # frozen_string_literal: true
  2. module AccountFinderConcern
  3. extend ActiveSupport::Concern
  4. class_methods do
  5. def find_local!(username)
  6. find_local(username) || raise(ActiveRecord::RecordNotFound)
  7. end
  8. def find_remote!(username, domain)
  9. find_remote(username, domain) || raise(ActiveRecord::RecordNotFound)
  10. end
  11. def find_local(username)
  12. find_remote(username, nil)
  13. end
  14. def find_remote(username, domain)
  15. AccountFinder.new(username, domain).account
  16. end
  17. end
  18. class AccountFinder
  19. attr_reader :username, :domain
  20. def initialize(username, domain)
  21. @username = username
  22. @domain = domain
  23. end
  24. def account
  25. scoped_accounts.take
  26. end
  27. private
  28. def scoped_accounts
  29. Account.unscoped.tap do |scope|
  30. scope.merge! with_usernames
  31. scope.merge! matching_username
  32. scope.merge! matching_domain
  33. end
  34. end
  35. def with_usernames
  36. Account.where.not(username: [nil, ''])
  37. end
  38. def matching_username
  39. Account.where(Account.arel_table[:username].lower.eq username.to_s.downcase)
  40. end
  41. def matching_domain
  42. if domain.nil?
  43. Account.where(domain: nil)
  44. else
  45. Account.where(Account.arel_table[:domain].lower.eq domain.to_s.downcase)
  46. end
  47. end
  48. end
  49. end