Module: Ecoportal::API::Common::Content::DocHelpers

Included in:
HashDiffPatch, V2::Pages, V2::Pages::Stages, V2::Registers
Defined in:
lib/ecoportal/api/common/content/doc_helpers.rb

Instance Method Summary collapse

Instance Method Details

#array_id_index(arr, id) ⇒ Integer

Helper used to identify in an Array the position of an object with certain id

Parameters:

  • doc (Array)

    the source Array

Returns:

  • (Integer)

    the position thereof



49
50
51
52
# File 'lib/ecoportal/api/common/content/doc_helpers.rb', line 49

def array_id_index(arr, id)
  return unless arr.is_a?(Array)
  arr.index {|item| get_id(item, exception: false) == id}
end

#array_id_item(arr, id) ⇒ Integer

Helper used to get in an Array and object item with certain id

Parameters:

  • doc (Array)

    the source Array

Returns:

  • (Integer)

    the object with that id



57
58
59
60
61
# File 'lib/ecoportal/api/common/content/doc_helpers.rb', line 57

def array_id_item(arr, id)
  if idx = array_id_index(arr, id)
    arr[idx]
  end
end

#array_ids(arr) ⇒ Array<String>

Helper used to identify the id s of objects contained in an Array

Parameters:

  • doc (Array)

    the source Array

Returns:

  • (Array<String>)

    the id s thereof



41
42
43
44
# File 'lib/ecoportal/api/common/content/doc_helpers.rb', line 41

def array_ids(arr)
  return [] if !arr.is_a?(Array) || arr.empty?
  arr.map {|item| get_id(item, exception: false)}
end

#get_body(doc, level: "page") ⇒ Hash?

Helper used to build the body of an HTTP request

Parameters:

  • doc (Page, Hash)

    hashable object

Returns:

  • (Hash, nil)

    the patch formated data ready to include as body of a HTTP request



10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/ecoportal/api/common/content/doc_helpers.rb', line 10

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)
        HashDiffPatch.patch_diff(doc.as_json, nil)
      when doc.is_a?(Hash)
        HashDiffPatch.patch_diff(doc, nil)
      else
        raise "Could not get body for doc: #{doc}"
      end
  end
end

#get_id(doc, exception: true) ⇒ Hash?

Helper used to identify the id of the target object

Parameters:

  • doc (Page, Hash)

    hashable object

  • exception (Boolean) (defaults to: true)

    states if id must be present

Returns:

  • (Hash, nil)

    the patch formated data ready to include as body of a HTTP request



29
30
31
32
33
34
35
36
# File 'lib/ecoportal/api/common/content/doc_helpers.rb', line 29

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