Module: DocumentHydrator

Defined in:
lib/document_hydrator/inflector/inflections.rb,
lib/document_hydrator.rb,
lib/document_hydrator/inflector.rb,
lib/document_hydrator/hydration_proc/mongo.rb

Overview

Extracted from ActiveSupport::Inflector in ActiveSupport 3.0.9.

Defined Under Namespace

Modules: HydrationProc, Inflector

Class Method Summary collapse

Class Method Details

.hydrate_document(document, path_or_paths, hydration_proc) ⇒ Object

Given a document hash, a path or array of paths describing locations of object IDs within the hash, and a function that will convert object IDs to a hash of subdocument hashes indexed by object ID, modifies the document hash so that all of the IDs referenced by the paths are replaced with the corresponding subdocuments.

Path examples:

document = {
  'owner' => 99,
  'clients' => [100, 101],
  'comments' => [
    { 'user' => 10, text => 'hi' },
    { 'user' => 11, text => 'hello' }
  ]
}

Each of these are valid paths:

- 'owner'
- 'clients'
- 'comments.user'

Returns the document to allow for chaining.



30
31
32
33
# File 'lib/document_hydrator.rb', line 30

def hydrate_document(document, path_or_paths, hydration_proc)
  hydrate_documents([document],path_or_paths, hydration_proc)
  document
end

.hydrate_documents(documents, path_or_paths, hydration_proc) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/document_hydrator.rb', line 35

def hydrate_documents(documents, path_or_paths, hydration_proc)
  # Traverse the documents replacing each ID with a corresponding dehydrated document
  dehydrated_subdocuments = Hash.new { |h, k| h[k] = Hash.new }
  documents.each do |document|
    paths = path_or_paths.kind_of?(Array) ? path_or_paths : [path_or_paths]
    paths.each do |path|
      replace_ids_with_dehydrated_documents(document, path.split('.'), dehydrated_subdocuments)
    end
  end

  # Rehydrate the documents that we discovered during traversal all in one go
  ids = dehydrated_subdocuments.keys
  hydrated_subdocuments = hydration_proc.call(ids)
  ids.each {|id| dehydrated_subdocuments[id].replace(hydrated_subdocuments[id])}

  documents
end