I want to write my own ActiveRecord cache, only for find_by_id
right now. To do this, I want to rewrite the find method when only one int is given, use my cache, otherwise use the default implementation.
class X < ActiveRecord::Base def self.find(*args) return XCache[args[0]] if args.size == 1 && args[0].is_a?(Numeric) return super.find(*args) end end
Everything works, except for the case of communication that I have with other X instances, for example. parent-child relationship:
has_many :x_children has_many :children, :class_name => "X", :through => :x_children
When I call X.find(1).children
, I get an Enumerator
instead of Array
, which is bad, because sometimes I use the [] operator.
Even using an enumerator does not work well - when I repeat the last record, I get:
NoMethodError: undefined method `call' for :all:Symbol
Any help would be greatly appreciated
Further explanation:
XCache is just a class that caches ActiveRecord instances. The simplest implementation could be
class XCache @@cache = {} def self.[id] return @@cache[id] ||= X.find(id) end end
(A more complex implementation may include expiration time, Memcached, etc., and a more general solution may support several classes of models).
I donβt think my problem is with cache implementation (but I could be wrong)