menu_item_update_action.rb 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. class KnowledgeBase
  2. class MenuItemUpdateAction
  3. def initialize(kb_locale, menu_items_data)
  4. @kb_locale = kb_locale
  5. @menu_items_data = menu_items_data
  6. end
  7. def perform!
  8. raise_unprocessable unless all_ids_present?
  9. KnowledgeBase::MenuItem.transaction do
  10. KnowledgeBase::MenuItem.acts_as_list_no_update do
  11. remove_deleted
  12. update_order
  13. end
  14. end
  15. end
  16. private
  17. def update_order
  18. old_items = @kb_locale.menu_items.to_a
  19. @menu_items_data
  20. .reject { |elem| elem[:_destroy] }
  21. .each_with_index do |data_elem, index|
  22. item = old_items.find { |record| record.id == data_elem[:id] } || @kb_locale.menu_items.build
  23. item.position = index
  24. item.title = data_elem[:title]
  25. item.url = data_elem[:url]
  26. item.new_tab = data_elem[:new_tab]
  27. item.save!
  28. end
  29. end
  30. def remove_deleted
  31. @menu_items_data
  32. .select { |elem| elem[:_destroy] }
  33. .map { |elem| elem[:id] }
  34. .tap { |array| @kb_locale.menu_items.where(id: array).destroy_all }
  35. end
  36. def all_ids_present?
  37. old_ids = @kb_locale.menu_items.pluck(:id)
  38. new_ids = @menu_items_data.map { |elem| elem[:id]&.to_i }.compact
  39. old_ids.sort == new_ids.sort
  40. end
  41. def raise_unprocessable
  42. raise Exceptions::UnprocessableEntity, 'Provide position of all items in scope'
  43. end
  44. end
  45. end