Sha256: 43990b35d61748687fd7b343cef59a699dcd0d55a0ba25eb75c39727f964d339

Contents?: true

Size: 1.44 KB

Versions: 4

Compression:

Stored size: 1.44 KB

Contents

module Ecoportal
  module API
    class V2
      class Page
        class Component
          class ChecklistField < Page::Component
            embeds_many :items, klass: "Ecoportal::API::V2::Page::Component::ChecklistItem", order_key: :weight

            def add_item(label:, pos: NOT_USED, before: NOT_USED, after: NOT_USED)
              itm_doc = items.items_class.new_doc
              items.upsert!(itm_doc, pos: pos, before: before, after: after) do |item|
                item.label  = label
                if prev = previous_item(item)
                  item.weight = prev.weight
                end
                yield(item) if block_given?
                fix_item_weights!
              end
            end

            def ordered_items
              items.each_with_index.sort_by do |item, index|
                (item.weight >= 9999) ? [index, index] : [item.weight, index]
              end.map(&:first)
            end

            private

            def fix_item_weights!
              ordered_items.each_with_index do |item, index|
                item.weight = index
              end
            end

            def previous_item(value)
              itms = ordered_items
              pos  = itms.index(value) - 1
              return if pos < 0
              itms[pos]
            end

          end
        end
      end
    end
  end
end

require 'ecoportal/api/v2/page/component/checklist_item'

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
ecoportal-api-v2-0.8.12 lib/ecoportal/api/v2/page/component/checklist_field.rb
ecoportal-api-v2-0.8.11 lib/ecoportal/api/v2/page/component/checklist_field.rb
ecoportal-api-v2-0.8.10 lib/ecoportal/api/v2/page/component/checklist_field.rb
ecoportal-api-v2-0.8.9 lib/ecoportal/api/v2/page/component/checklist_field.rb