I''ve created this class that overrides methods for
find,delete,destroy,reload, and save in activeresource. The code
populates a local memcache daemon and uses that cache for future find
requests. I''m posting it here to get whatever feedback people have.
I''m most interested in the pro/con of inheritance over a mixin and how
such a module might be tested.
$ cat lib/cached_resource.rb
# CachedResource uses memcache to cache HTTP responses from a
# RESTful web application.
#
class CachedResource < ActiveResource::Base
begin
@@cache = MemCache.new(''localhost'')
# test the connection to the Memcache server
@@cache.get(1)
rescue MemCache::MemCacheError
@@cache = nil
end
# See ActiveResource::Base.find for method description
def self.find(*args)
if args.length == 1 && args.first.is_a?(Fixnum)
cached_record = self.cache_read(args.first)
return cached_record if cached_record
end
# if find(int) is not a cache hit or if the
# find is more complex, do the find as normal
# and cache the answers
records = super(*args)
case records
when Array
records.each {|r| r.cache_write}
else
records.cache_write
end
return records
end
# See ActiveResource::Base.delete for method description
def self.delete(*args)
if args.length == 1 && args.first.is_a?(Fixnum)
self.cache_delete
end
super(*args)
end
# See ActiveResource::Base.destroy for method description
def destroy
self.cache_delete
super
end
# See ActiveResource::Base.reload for method description
def reload
self.cache_delete
# This is lifted from ActiveResource::Base.reload and modified
# to pass along the grant argument.
self.load self.class.find(id, @prefix_options).attributes
end
# See ActiveResource::Base.reload for method description
def save
super
self.cache_write
end
def self.build_cache_key(id)
"#{name}:#{id}"
end
def self.cache_read(id)
@@cache.get(self.build_cache_key(id)) if @@cache
end
def self.cache_delete(id)
@@cache.delete(self.build_cache_key(id)) if @@cache
end
def cache_key
self.class.build_cache_key(self.id)
end
def cache_write
@@cache.set(self.cache_key,self) if @@cache
end
def cache_delete
@@cache.delete(self.cache_key) if @@cache
end
end
Thanks,
Don
ps. The code above is released under the same license as the ruby language.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---