Sha256: 52d9e250ece8b4d2ae5d7a2dbfd204a9308de3806baee722398c04d6e4e23c17

Contents?: true

Size: 1.8 KB

Versions: 11

Compression:

Stored size: 1.8 KB

Contents

if defined?(Mongoid)

  module Hancock

    # Helps to override find method in an embedded document.
    # Usage :
    #   - add to your model "include Hancock::EmbeddedFindable"
    #   - override find method with:
    #     def self.find(id)
    #       find_through(Book, 'chapter', id)
    #     end
    module EmbeddedFindable

      extend ActiveSupport::Concern

      included do

        # Search an embedded document by id.
        #
        # Document is stored within embedding_class collection, and can be accessed through provided relation.
        # Also supports chained relationships (if the searched document is nested in several embedded documents)
        #
        # Example, with a chapter embedded in a book, the book being embedded in a library.
        # use find_through(Library, "books", book_id) in Book class
        # and find_through(Library, "books.chapters", chapter_id) in Chapter class
        def self.find_through(embedding_class, relation, id = nil)
          return nil if id.nil? || id.blank?

          id = BSON::ObjectId.from_string(id) if id.is_a?(String)
          relation = relation.to_s unless relation.is_a?(String)

          relation_parts = relation.split('.')
          parent = embedding_class.send(:all)

          while relation_parts.length > 0
            item = if parent.is_a?(Mongoid::Criteria) || parent.is_a?(Array)
                     parent.where("#{relation_parts.join('.')}._id" => id).first
                   else
                     parent
                   end
            return nil if item.nil?
            parent = item.send(relation_parts.shift)
          end

          if parent.is_a?(Mongoid::Criteria) || parent.is_a?(Array)
            parent.where('_id' => id).first
          else
            parent
          end
        end

      end

    end

  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
hancock_cms-2.0.1.3 app/models/concerns/hancock/embedded_findable.rb
hancock_cms-1.0.2.3 app/models/concerns/hancock/embedded_findable.rb
hancock_cms-2.0.1.2 app/models/concerns/hancock/embedded_findable.rb
hancock_cms-2.0.1.1 app/models/concerns/hancock/embedded_findable.rb
hancock_cms-1.0.2.2 app/models/concerns/hancock/embedded_findable.rb
hancock_cms-1.0.1 app/models/concerns/hancock/embedded_findable.rb
hancock_cms-2.0.0.2 app/models/concerns/hancock/embedded_findable.rb
hancock_cms-1.0.0.4 app/models/concerns/hancock/embedded_findable.rb
hancock_cms-1.0.0.3 app/models/concerns/hancock/embedded_findable.rb
hancock_cms-2.0.0.1 app/models/concerns/hancock/embedded_findable.rb
hancock_cms-1.0.0.2 app/models/concerns/hancock/embedded_findable.rb