Sha256: daf0103761acadd8f2739b466a374b7c2296054f279db57c3460123433736f65

Contents?: true

Size: 1.51 KB

Versions: 16

Compression:

Stored size: 1.51 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.sort_by.with_index do |item, index|
                [item.weight, index]
              end
            end

            def to_s(delimiter: "\n")
              ordered_items.map(&:to_s).compact.join(delimiter)
            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

16 entries across 16 versions & 1 rubygems

Version Path
ecoportal-api-v2-0.9.3 lib/ecoportal/api/v2/page/component/checklist_field.rb
ecoportal-api-v2-0.9.2 lib/ecoportal/api/v2/page/component/checklist_field.rb
ecoportal-api-v2-0.9.1 lib/ecoportal/api/v2/page/component/checklist_field.rb
ecoportal-api-v2-0.8.33 lib/ecoportal/api/v2/page/component/checklist_field.rb
ecoportal-api-v2-0.8.32 lib/ecoportal/api/v2/page/component/checklist_field.rb
ecoportal-api-v2-0.8.31 lib/ecoportal/api/v2/page/component/checklist_field.rb
ecoportal-api-v2-0.8.30 lib/ecoportal/api/v2/page/component/checklist_field.rb
ecoportal-api-v2-0.8.29 lib/ecoportal/api/v2/page/component/checklist_field.rb
ecoportal-api-v2-0.8.28 lib/ecoportal/api/v2/page/component/checklist_field.rb
ecoportal-api-v2-0.8.27 lib/ecoportal/api/v2/page/component/checklist_field.rb
ecoportal-api-v2-0.8.26 lib/ecoportal/api/v2/page/component/checklist_field.rb
ecoportal-api-v2-0.8.25 lib/ecoportal/api/v2/page/component/checklist_field.rb
ecoportal-api-v2-0.8.24 lib/ecoportal/api/v2/page/component/checklist_field.rb
ecoportal-api-v2-0.8.23 lib/ecoportal/api/v2/page/component/checklist_field.rb
ecoportal-api-v2-0.8.22 lib/ecoportal/api/v2/page/component/checklist_field.rb
ecoportal-api-v2-0.8.21 lib/ecoportal/api/v2/page/component/checklist_field.rb