organized flames

Simple Rails Caching

Posted on October 28, 2007 by Michael

In my apache configuration I have Apache serving static pages from the public directory. After playing around with Mephisto a bit, I’ve learned a few tricks on caching.

The common belief is to use memcache for caching on sites that are large enough to need it. However, I think with a few tricks, I can do better. I think in some cases, letting Apache serve the content is a far wiser move.

For example, I will begin writing out the images for avatars on guildcorner.org to files, and let Apache serve them. I will do this when they are created, updated, or rendered to a browser. This will let Apache serve the next request for it. I also plan on deleting the cache file if the avatar is deleted.

Since I use Capistrano to push out releases now, and the cached files are not in subversion, upgrading to a new application version won’t require anything special.

RailsMode (not ENV['production'])

Posted on October 27, 2007 by Michael

RailsMode

I’ve been spreading things like this all around my code, where I wanted to do something differently in production vs. development mode. Previously, I’d write something like this:

  1. if ENV[RAILS_ENV] == production
  2. … perform magic …
  3. end

While this is pretty simple, it just didn’t feel very DRY. So, I decided to use this as a reason to learn about modules and mixins.

I have a generic plug-in in vendor/plugins that I put small bits of code like this. You might as well, but if you don’t, you can drop this in a helper.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

module RailsMode
  def railsmode(*list)
    list.map! do |item|
      item.to_s
    end

    if block_given?
      if list.include?(ENV['RAILS_ENV'])
        yield
      end
    else
      return list.include?(ENV['RAILS_ENV'])
    end
  end
end

I also put this line in my environment.rb file:

1
2

include RailsMode

This mixes the module into the current class. Doing this in environment.rb makes it available everywhere in rails. Putting that line in a specific file would also work, such as a controller, or a helper.

With this, I can now write:

1
2
3
4

if railsmode(:production)
  ... perform magic ...
end

I can also check for multiple modes at once:

1
2
3
4

if railsmode(:production, :development)
  ... perform magic ...
end

And of course, who needs an if when I can pass in a block:

1
2
3
4

railsmode(:production) do
  ... perform magic ...
end