Sha256: ad91285b468a2b8dfc2e2822b35f7525e927c6904a703868990018820b339e45

Contents?: true

Size: 1.46 KB

Versions: 3

Compression:

Stored size: 1.46 KB

Contents

module Ecoportal
  module API
    class V2
      class Page
        class Component
          class FilesField < Page::Component
            embeds_many :items, klass: "Ecoportal::API::V2::Page::Component::File", order_key: :position

            def add_file(container_id, pos: NOT_USED, before: NOT_USED, after: NOT_USED)
              file_doc = items.items_class.new_doc
              items.upsert!(file_doc, pos: pos, before: before, after: after) do |file|
                file.file_container_id  = container_id
                if prev = previous_file(file)
                  file.position = prev.position
                end
                yield(file) if block_given?
                fix_file_positions!
              end
            end

            def ordered_files
              items.each_with_index.sort_by do |file, index|
                (file.position >= 9999) ? [index, index] : [file.position, index]
              end.map(&:first)
            end

            private

            def fix_file_positions!
              ordered_files.each_with_index do |file, index|
                file.position = index
              end
            end

            def previous_file(value)
              fls = ordered_files
              pos = fls.index(value) - 1
              return if pos < 0
              fls[pos]
            end

          end
        end
      end
    end
  end
end

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

Version data entries

3 entries across 3 versions & 1 rubygems

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