Last active
December 25, 2015 13:09
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# 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