Skip to content

Instantly share code, notes, and snippets.

@leifcr
Last active December 25, 2015 13:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leifcr/6981688 to your computer and use it in GitHub Desktop.
Save leifcr/6981688 to your computer and use it in GitHub Desktop.
Get dot notation for a embedded mongoid element (Going upwards in the "embedded_in" hierarchy)
#
# Get dot notification for the current mongoid element
#
def dot_notation_for_element(element)
return "" if element.nil?
dot_notation = dot_notation_for_element_nested(element)
if dot_notation.nil?
return ""
else
dot_notation[0] = ''
end
dot_notation
end
#
# Get dot notification for nested elements (nesting updwards)
#
def dot_notation_for_element_nested(element)
# Get non-nil_embedded_relation
p = get_embedded_relation(element)
# puts p.inspect
if p.nil?
return nil
else
"#{dot_notation_for_element_nested(p[0])}.#{p[1].inverse_of}"
end
end
#
# Returns array [p, r], where p is the parent element for the embedded element, and
# r is the inverse reflection name
#
def get_embedded_relation(element)
element.reflect_on_all_associations(:embedded_in).each do |r|
# puts r.inspect
p = element.send(r.name.to_s)
return [p, r] unless p.nil?
end
nil
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment