Created
December 2, 2009 02:10
-
-
Save mattetti/246867 to your computer and use it in GitHub Desktop.
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
# let's pretend we are not dealing with Rails, AR or even a DB | |
# controller | |
def index | |
@kids = Kid.fetch | |
end | |
# view | |
<ul> | |
<%- @kids.each do |kid| -%> | |
<li><%= kid.name %> children of <%= kid.father.name %></li> | |
<%- end -%> | |
</ul> | |
# the problem is that we are going to fetch each kid's father even though in a family | |
# all kids have the same father (in theory). | |
# to avoid to go fetch the same object over and over we could do that: | |
# controller | |
def index | |
@kids = Kid.fetch | |
fetch_and_cache_kids_fathers(@kids) | |
end | |
def fetch_and_cache_kids_fathers(kids) | |
father_refs = kids.map{|k| k.father_ref} | |
fathers = Adult.fetch(father_refs) | |
kids.each |kid| | |
kid.instance_variable_set("@cached_father", father_refs.find{|dad| dad.ref == kid.father_ref}) | |
def kid.father | |
@cached_father.nil? ? super : @cached_father | |
end | |
end | |
end | |
# view doesn't have to be changed | |
## What do you think? | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment