Sha256: a6a6ad6f3124cdeb2e8cda43b7b3d34b897f8460677878601be49962e0d3a4ef

Contents?: true

Size: 1.39 KB

Versions: 2

Compression:

Stored size: 1.39 KB

Contents

# frozen_string_literal: true
module Mongoid
  module Findable
    delegate :pluck_all, :pluck_array, to: :with_default_scope
  end

  module Contextual
    delegate :pluck_all, :pluck_array, to: :context

    class None
      def pluck_array(*)
        []
      end

      def pluck_all(*)
        []
      end
    end

    class Mongo
      def pluck_array(*fields)
        normalized_select = get_normalized_select(fields)
        get_query_data(normalized_select).reduce([]) do |plucked, doc|
          values = normalized_select.keys.map do |n|
            n =~ /\./ ? doc[n.partition('.')[0]] : doc[n]
          end
          plucked << (values.size == 1 ? values.first : values)
        end
      end

      def pluck_all(*fields)
        normalized_select = get_normalized_select(fields)
        get_query_data(normalized_select).reduce([]) do |plucked, doc|
          values = normalized_select.keys.map do |n|
            [n, n =~ /\./ ? doc[n.partition('.')[0]] : doc[n]]
          end.to_h
          plucked << values
        end
      end

      private

      def get_query_data(normalized_select)
        return (@view ? @view.projection(normalized_select) : query.dup.select(normalized_select))
      end

      def get_normalized_select(fields)
        normalized_select = fields.inject({}) do |hash, f|
          hash[klass.database_field_name(f)] = 1
          hash
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
pluck_all-2.0.1 lib/pluck_all/mongoid_pluck_all.rb
pluck_all-2.0.0 lib/pluck_all/mongoid_pluck_all.rb