123456789_123456789_123456789_123456789_123456789_

Module: Mongoid::Attributes::Embedded

Relationships & Source Files
Defined in: lib/mongoid/attributes/embedded.rb

Overview

Utility module for working with embedded attributes.

Instance Method Summary

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.

[ GitHub ]

  
# 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