Sha256: 76877404c7a62dcc6ba6ce730acd74609556cf18ee9ed35a7a74432192a3f158

Contents?: true

Size: 1.09 KB

Versions: 12

Compression:

Stored size: 1.09 KB

Contents

# frozen_string_literal: true

require 'active_support'

class DHS::Collection < DHS::Proxy

  # Handles pontentially (deep-)nested collections
  #   Examples:
  #     [ { name: 'Steve '} ]
  #     { items: [ { name: 'Steve' } ] }
  #     { response: { business: [ { name: 'Steve' } ] } }
  module HandleNested
    extend ActiveSupport::Concern

    delegate :access, :nest, :concat, to: :class

    module ClassMethods
      # Access potentially nested collection of items
      def access(input:, record: nil)
        input.dig(*items_key(record))
      end

      # Initializes nested collection
      def nest(input:, value: nil, record: nil)
        input[items_key(record)] = value
      end

      # Concats existing nested collection of items
      # with given items
      def concat(input:, items:, record: nil)
        input.dig(*items_key(record)).concat(items)
      end

      private

      # Takes configured items key to access collection of items
      # of falls back to the default key
      def items_key(record)
        record&.items_key || DHS::Record.items_key
      end
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
dhs-1.6.0 lib/dhs/concerns/collection/handle_nested.rb
dhs-1.5.0 lib/dhs/concerns/collection/handle_nested.rb
dhs-1.4.2 lib/dhs/concerns/collection/handle_nested.rb
dhs-1.4.1 lib/dhs/concerns/collection/handle_nested.rb
dhs-1.4.0 lib/dhs/concerns/collection/handle_nested.rb
dhs-1.3.0 lib/dhs/concerns/collection/handle_nested.rb
dhs-1.2.0 lib/dhs/concerns/collection/handle_nested.rb
dhs-1.1.0 lib/dhs/concerns/collection/handle_nested.rb
dhs-1.0.3 lib/dhs/concerns/collection/handle_nested.rb
dhs-1.0.2 lib/dhs/concerns/collection/handle_nested.rb
dhs-1.0.1 lib/dhs/concerns/collection/handle_nested.rb
dhs-1.0.0 lib/dhs/concerns/collection/handle_nested.rb