can_lookup.rb 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. # Copyright (C) 2012-2023 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. return find_by(attr) if columns.exclude?('updated_at')
  19. Rails.cache.fetch("#{self}/#{latest_change}/lookup/#{Digest::MD5.hexdigest(Marshal.dump(attr))}") do
  20. find_by(attr)
  21. end
  22. end
  23. =begin
  24. return possible lookup keys for model
  25. result = Model.lookup_keys
  26. returns
  27. [:id, :name] # or, for users: [:id, :login, :email]
  28. =end
  29. def lookup_keys
  30. @lookup_keys ||= %i[id name login email number] & attribute_names.map(&:to_sym)
  31. end
  32. end
  33. end