can_lookup.rb 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. module ApplicationModel::CanLookup
  3. extend ActiveSupport::Concern
  4. class_methods do
  5. =begin
  6. lookup model from cache (if exists) or retrieve it from db, id, name, login or email possible
  7. result = Model.lookup(id: 123)
  8. result = Model.lookup(name: 'some name')
  9. result = Model.lookup(login: 'some login')
  10. result = Model.lookup(email: 'some login')
  11. returns
  12. result = model # with all attributes
  13. =end
  14. def lookup(**attr)
  15. raise ArgumentError, "Multiple lookup attributes given (#{attr.keys.join(', ')}), only support (#{lookup_keys.join(', ')})" if attr.many?
  16. attr.transform_keys!(&:to_sym).slice!(*lookup_keys)
  17. raise ArgumentError, "Valid lookup attribute required (#{lookup_keys.join(', ')})" if attr.empty?
  18. Auth::RequestCache.fetch_value("#{self}/lookup/#{Digest::MD5.hexdigest(Marshal.dump(attr))}") do
  19. find_by(attr)
  20. end
  21. end
  22. =begin
  23. return possible lookup keys for model
  24. result = Model.lookup_keys
  25. returns
  26. [:id, :name] # or, for users: [:id, :login, :email]
  27. =end
  28. def lookup_keys
  29. @lookup_keys ||= %i[id name login email number] & attribute_names.map(&:to_sym)
  30. end
  31. end
  32. end