Hi everyone,
I tend to be searching my association collections a lot for specific
field values. I could do a foo.bars.find_all_by_fieldname(fieldvalue)
each time, but why hit the database over again? Especially when the
full collection is already in memory. I wrote this module to extend
associations to look at the already loaded collection for field/value
matches.
module MyAssociationExtentions
def field_find(field, value, opts = {})
@field_cache = nil if opts[‘reload’]
((@field_cache ||= {field => {}})[field] ||= {})[value] ||=
self.is_a?(Enumerable) ? (self.select { |task| task.send(field) == value
}) : (self if self.send(field) == value)
end
end
Here it is again written out into multi lines so it is easier to read in
the forum
module MyAssociationExtentions
def field_find(field, value, opts = {})
@field_cache = nil if opts[‘reload’]
@field_cache = {} unless @field_cache
@field_cache[field] = {value => []} unless @field_cache[field]
@field_cache[field][value] ||= self.is_a?(Enumerable) ? (self.select
{ |task| task.send(field) == value }) : (self if self.send(field) ==
value)
end
end
Questions:
- I use a multi-dimentional hash to store each potential field/value
lookup. Is this too memory intensive? - Does this even theoretically improve performance vs the database? or
is it a waste of time - Is there a better way to write that line (all those annoying checks
to see if the hash is already there) - could I push this into memcache to lower the memory usage by
distributing it across mongrels.
Thanks