search_index_base.rb 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. # Copyright (C) 2012-2013 Zammad Foundation, http://zammad-foundation.org/
  2. module ApplicationModel::SearchIndexBase
  3. =begin
  4. collect data to index and send to backend
  5. ticket = Ticket.find(123)
  6. result = ticket.search_index_update_backend
  7. returns
  8. result = true # false
  9. =end
  10. def search_index_update_backend
  11. return if !self.class.search_index_support_config
  12. # default ignored attributes
  13. ignore_attributes = {
  14. :created_at => true,
  15. :updated_at => true,
  16. :created_by_id => true,
  17. :updated_by_id => true,
  18. :active => true,
  19. }
  20. if self.class.search_index_support_config[:ignore_attributes]
  21. self.class.search_index_support_config[:ignore_attributes].each {|key, value|
  22. ignore_attributes[key] = value
  23. }
  24. end
  25. # remove ignored attributes
  26. attributes = self.attributes
  27. ignore_attributes.each {|key, value|
  28. next if value != true
  29. attributes.delete( key.to_s )
  30. }
  31. # fill up with search data
  32. attributes = search_index_attribute_lookup(attributes, self)
  33. return if !attributes
  34. # update backend
  35. if self.class.column_names.include? 'active'
  36. if self.active
  37. SearchIndexBackend.add( self.class.to_s, attributes )
  38. else
  39. SearchIndexBackend.remove( self.class.to_s, self.id )
  40. end
  41. else
  42. SearchIndexBackend.add( self.class.to_s, attributes )
  43. end
  44. end
  45. private
  46. =begin
  47. lookup name of ref. objects
  48. attributes = search_index_attribute_lookup(attributes, Ticket)
  49. returns
  50. attributes # object with lookup data
  51. =end
  52. def search_index_attribute_lookup(attributes, ref_object)
  53. attributes_new = {}
  54. attributes.each {|key, value|
  55. next if !value
  56. # get attribute name
  57. attribute_name = key.to_s
  58. next if attribute_name[-3,3] != '_id'
  59. attribute_name = attribute_name[ 0, attribute_name.length-3 ]
  60. # check if attribute method exists
  61. next if !ref_object.respond_to?( attribute_name )
  62. # check if method has own class
  63. relation_class = ref_object.send(attribute_name).class
  64. next if !relation_class
  65. # lookup ref object
  66. relation_model = relation_class.lookup( :id => value )
  67. next if !relation_model
  68. # get name of ref object
  69. value = nil
  70. if relation_model['name']
  71. value = relation_model['name']
  72. elsif relation_model.respond_to?('fullname')
  73. value = relation_model.send('fullname')
  74. end
  75. next if !value
  76. # save name of ref object
  77. attributes_new[ attribute_name ] = value
  78. attributes.delete(key)
  79. }
  80. attributes_new.merge(attributes)
  81. end
  82. end