module Ecoportal module API module Common module Content module DocHelpers # Helper used to build the `body` of an HTTP request # @param doc [Page, Hash] hashable object # @return [Hash, nil] the `patch` formated `data` ready to include as `body` of a HTTP request def get_body(doc, level: "page") {}.tap do |body| body["#{level}"] = case when doc.respond_to?(:as_update) doc.as_update when doc.respond_to?(:as_json) Common::Content::HashPatchDiff.patch_diff(doc.as_json) when doc.is_a?(Hash) Common::Content::HashPatchDiff.patch_diff(doc) else raise "Could not get body for doc: #{doc}" end end end # Helper used to **identify** the `id` of the target object # @param doc [Page, Hash] hashable object # @param exception [Boolean] states if `id` **must** be present # @return [Hash, nil] the `patch` formated `data` ready to include as `body` of a HTTP request def get_id(doc, exception: true) id = nil id ||= doc.id if doc.respond_to?(:id) id ||= doc["id"] if doc.is_a?(Hash) id ||= doc if doc.is_a?(String) raise "No ID has been given!" unless id || !exception id end # Helper used to **identify** the `id` s of objects contained in an `Array` # @param doc [Array] the source Array # @return [Array] the `id` s thereof def array_ids(arr) return [] if !arr.is_a?(Array) || arr.empty? arr.map {|item| get_id(item, exception: false)} end # Helper used to **identify** in an Array the `position` of an object with certain `id` # @param doc [Array] the source Array # @return [Integer] the `position` thereof def array_id_index(arr, id) return unless arr.is_a?(Array) arr.index {|item| get_id(item, exception: false) == id} end # Helper used to **get** in an Array and `object` item with certain `id` # @param doc [Array] the source Array # @return [Integer] the `object` with that `id` def array_id_item(arr, id) if idx = array_id_index(arr, id) arr[idx] end end end end end end end