[Noisebridge-discuss] Where to patch Rails ActiveRecord::find() to first check collections in memory?

Sai Emrys noisebridge at saizai.com
Sun Oct 4 07:52:56 UTC 2009


Already put it up on StackOverflow:
http://stackoverflow.com/questions/1515856/where-to-patch-rails-activerecordfind-to-first-check-collections-in-memory
... but I figured there's got to be a couple Rails hackers around here
who might be interested.


For somewhat complicated reasons, I would like to create something
that works like this:

# Controller:
@comments = @page.comments # comments are threaded
# child comments still belong to @page
...
# View:

@comments.each_root {
  display @comment {
    indent & recurse on @comment.children
} }

# alternatives for how recursion call might work:

# first searches @comments, then actually goes to SQL
comment.in_memory.children

# only looks at @comments, RecordNotFound if not there
# better if we know @comments is complete, and checking for nonexistent
#  records would be wasteful
comment.in_memory(:only).children

# the real thing - goes all the way to DB even though target is already in RAM
# ... but there's no way for find() to realize that :(
comment.children


I'm not even sure yet if this is possible, let alone a good idea, but
I'm curious, and it'd be helpful.

Basically I want to redirect find() so that it looks first/only at the
collection that's already been loaded, using something like a
hypothetical @collection.find{|item| item.matches_finder_sql(...)}.

The point is to prevent unnecessarily complex caching and expensive
database lookups for stuff that's already been loaded en masse.

If possible, it'd be nice if this played nice with extant mechanisms
for staleness, association lazy loading, etc.

The nested-comments thing is just an example; of course this applies
to lots of other situations too.

So... how could I do this?

- Sai



More information about the Noisebridge-discuss mailing list