views:

37

answers:

1

With RoR, you have your model, controller and view.

The model has both class properties etc., and db access code mingled in.

In your controllers, you use your models to fetch certain data to push to your views.

In the Java world, you would have a DAO per entity, and then a 'Service' layer where you could decide to pull the object from cache or fetch from your DAO.

What do Rails people do?

+3  A: 

Assuming your want to use Memcached as caching layer, you might probably be happy to know that the Rails caching architecture already supports Memcached storage. Just configure it in your application.rb file (assuming you are using Rails 3):

module MyApp
  class Application < Rails::Application

    config.cache_store = :dalli_store

  end
end

Here I'm using the :dalli_store which is provided by the Dalli gem, an high performance Memcached client. Rails ships with a standard :memcached store, so you can use it if you want.

Then, once configured, you can access your cache layer using Rails.cache.

  • Rails.cache.write
  • Rails.cache.read
  • Rails.cache.fetch
  • Rails.cache.delete

For instance, let's say you want to cache an expensive ActiveRecord query.

class Post < ActiveRecord::Base
  def expensive_query
    Rails.cache.fetch("posts/expensive_query") do
      where("1 = 1").all
    end
  end
end

The first time, when the cache is not available, #fetch will execute the content of the block and cache it. Later, the cache will simply be returned.

Simone Carletti