account_finder_concern.rb 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 representative
  12. Account.find(-99)
  13. end
  14. def find_local(username)
  15. find_remote(username, nil)
  16. end
  17. def find_remote(username, domain)
  18. AccountFinder.new(username, domain).account
  19. end
  20. end
  21. class AccountFinder
  22. attr_reader :username, :domain
  23. def initialize(username, domain)
  24. @username = username
  25. @domain = domain
  26. end
  27. def account
  28. scoped_accounts.order(id: :asc).take
  29. end
  30. private
  31. def scoped_accounts
  32. Account.unscoped.tap do |scope|
  33. scope.merge! with_usernames
  34. scope.merge! matching_username
  35. scope.merge! matching_domain
  36. end
  37. end
  38. def with_usernames
  39. Account.where.not(username: '')
  40. end
  41. def matching_username
  42. Account.where(Account.arel_table[:username].lower.eq username.to_s.downcase)
  43. end
  44. def matching_domain
  45. if domain.nil?
  46. Account.where(domain: nil)
  47. else
  48. Account.where(Account.arel_table[:domain].lower.eq domain.to_s.downcase)
  49. end
  50. end
  51. end
  52. end