Sha256: 37e991971459e35940da31e5d3cb5bb7824a9ea7962e4335bd8be905e596e895

Contents?: true

Size: 1.41 KB

Versions: 2

Compression:

Stored size: 1.41 KB

Contents

# encoding: utf-8
module Mongoid #:nodoc:
  module Paths #:nodoc:
    extend ActiveSupport::Concern
    included do
      cattr_accessor :_path, :_position
      delegate :_path, :_position, :to => "self.class"
    end
    module InstanceMethods
      # Return the path to this +Document+ in JSON notation, used for atomic
      # updates via $set in MongoDB.
      #
      # Example:
      #
      # <tt>address.path # returns "addresses"</tt>
      def path
        self._path ||= climb("") do |document, value|
          value = "#{document.association_name}#{"." + value unless value.blank?}"
        end
      end

      # Returns the positional operator of this document for modification.
      #
      # Example:
      #
      # <tt>address.position</tt>
      def position
        self._position ||= (path.blank? ? "" : "#{path}.$")
      end

      # Return the selector for this document to be matched exactly for use
      # with MongoDB's $ operator.
      #
      # Example:
      #
      # <tt>address.selector</tt>
      def selector
        @selector ||= climb({ "_id" => _root.id }) do |document, value|
          value["#{document.path}._id"] = document.id; value
        end
      end

      protected
      def climb(value, &block)
        document = self;
        while (document._parent) do
          value = yield document, value
          document = document._parent
        end
        value
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 2 rubygems

Version Path
mongoid-pre-2.0.0.beta1 lib/mongoid/paths.rb
mongoid-2.0.0.alpha lib/mongoid/paths.rb