Created
October 19, 2012 12:39
-
-
Save phillbaker/3918047 to your computer and use it in GitHub Desktop.
DataMapper semi-equivalent of ActiveRecord's reflect_on_all_associations method
This file contains hidden or 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
# Originally http://pastie.org/pastes/233178 | |
def reflect_on_all_associations | |
# Datamapper, you're crazy... | |
relationships.map { |name, relationship| | |
#TODO :has_and_belongs_to_many | |
if relationship.options[:min].nil? | |
macro = :belongs_to | |
if relationship.options[:class_name] | |
# In a belongs_to, the side with the class name uses | |
# the parent model, but child key for the foreign key... | |
class_name = relationship.parent_model.to_s | |
primary_key_name = relationship.child_key.entries.first.name | |
else | |
class_name = relationship.child_model.to_s | |
primary_key_name = relationship.parent_key.entries.first.name | |
end | |
else | |
macro = :has_one | |
if relationship.options[:class_name] | |
# but on the has_one side, it's the *child* model that | |
# uses the child key for the foreign key. Weirdness. | |
class_name = relationship.child_model.to_s | |
primary_key_name = relationship.child_key.entries.first.name | |
else | |
class_name = relationship.parent_model.to_s | |
primary_key_name = relationship.parent_key.entries.first.name | |
end | |
end | |
OpenStruct.new( | |
:name => name, | |
:class_name => class_name, | |
:primary_key_name => primary_key_name, | |
:macro => macro | |
) | |
} | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment