account_finder_concern.rb 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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(Account.arel_table[:username].lower.eq '')
  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. Account.where(Account.arel_table[:domain].lower.eq(domain.nil? ? nil : domain.to_s.downcase))
  46. end
  47. end
  48. end