Module: Mongoid::Attributes::Embedded

Extended by:
Embedded
Included in:
Embedded
Defined in:
lib/mongoid/attributes/embedded.rb

Overview

Utility module for working with embedded attributes.

Instance Method Summary collapse

Instance Method Details

#traverse(attributes, path) ⇒ Object | nil

Fetch an embedded value or subset of attributes via dot notation.

Examples:

Fetch an embedded value via dot notation.

Embedded.traverse({ 'name' => { 'en' => 'test' } }, 'name.en')
#=> 'test'

Parameters:

  • attributes (Hash)

    The document attributes.

  • path (String)

    The dot notation string.

Returns:

  • (Object | nil)

    The attributes at the given path, or nil if the path doesn’t exist.



20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/mongoid/attributes/embedded.rb', line 20

def traverse(attributes, path)
  path.split('.').each do |key|
    break if attributes.nil?

    attributes = if attributes.try(:key?, key)
                   attributes[key]
                 elsif attributes.respond_to?(:each) && key.match?(/\A\d+\z/)
                   attributes[key.to_i]
                 end
  end
  attributes
end