can_lookup.rb 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. # Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
  2. module ApplicationModel::CanLookup
  3. extend ActiveSupport::Concern
  4. # methods defined here are going to extend the class, not the instance of it
  5. class_methods do
  6. =begin
  7. lookup model from cache (if exists) or retrieve it from db, id, name, login or email possible
  8. result = Model.lookup(id: 123)
  9. result = Model.lookup(name: 'some name')
  10. result = Model.lookup(login: 'some login')
  11. result = Model.lookup(email: 'some login')
  12. returns
  13. result = model # with all attributes
  14. =end
  15. def lookup(data)
  16. if data[:id]
  17. cache = cache_get(data[:id])
  18. return cache if cache
  19. record = find_by(id: data[:id])
  20. cache_set(data[:id], record)
  21. return record
  22. elsif data[:name]
  23. cache = cache_get(data[:name])
  24. return cache if cache
  25. # do lookup with == to handle case insensitive databases
  26. records = if Rails.application.config.db_case_sensitive
  27. where('LOWER(name) = LOWER(?)', data[:name])
  28. else
  29. where(name: data[:name])
  30. end
  31. records.each do |loop_record|
  32. if loop_record.name == data[:name]
  33. cache_set(data[:name], loop_record)
  34. return loop_record
  35. end
  36. end
  37. return
  38. elsif data[:login]
  39. cache = cache_get(data[:login])
  40. return cache if cache
  41. # do lookup with == to handle case insensitive databases
  42. records = if Rails.application.config.db_case_sensitive
  43. where('LOWER(login) = LOWER(?)', data[:login])
  44. else
  45. where(login: data[:login])
  46. end
  47. records.each do |loop_record|
  48. if loop_record.login == data[:login]
  49. cache_set(data[:login], loop_record)
  50. return loop_record
  51. end
  52. end
  53. return
  54. elsif data[:email]
  55. cache = cache_get(data[:email])
  56. return cache if cache
  57. # do lookup with == to handle case insensitive databases
  58. records = if Rails.application.config.db_case_sensitive
  59. where('LOWER(email) = LOWER(?)', data[:email])
  60. else
  61. where(email: data[:email])
  62. end
  63. records.each do |loop_record|
  64. if loop_record.email == data[:email]
  65. cache_set(data[:email], loop_record)
  66. return loop_record
  67. end
  68. end
  69. return
  70. end
  71. raise ArgumentError, 'Need name, id, login or email for lookup()'
  72. end
  73. end
  74. end