Logical Model Caching

Your logical models sit atop the physical models, often transforming them in some way before returning them as the result of a service request. Later in this chapter, we’ll discuss how you can cache physical models; however, even with the majority of your physical models cached, the transformations required to turn them into logical model objects can be quite costly, too. Rather than recompute your logical model objects on each request, they too can be cached.

However, because existing tutorials do not treat logical and physical models differently, Rails websites today are not built with this principle in mind. As a consequence, there are no plugins currently available for easing logical model caching. Luckily, it’s easy to accomplish even without a plugin. In this section, you’ll see how to go about building a complete caching layer on your own.

To implement our caching, we’ll use Memcache. If you’re not already using it, download it, install it, install the memcache-client gem, and add the following to your environment.rb file:

CACHE = MemCache.new \
  :c_threshold => 10_000,
  :compression => false,
  :debug => false,
  :namespace => RAILS_ENV,
  :readonly => false,
  :urlencode => false

CACHE.servers = '127.0.0.1:11211'

To help illustrate how our caching scheme will work, we’ll return to the logical model for the Movie class from Chapter 15, shown in Example 15-3. Just as with our materialized view from Chapter 12, we’d like our interface to cached data ...

Get Enterprise Rails now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.