rails3 snippets

How to generate HAML views for Devise

Tagged devise, haml, rails3  Languages ruby

This will generate HAML views with Rails 3, HAML >=3.0.18 (won't work with lower version), and the latest devise version:

$ rails generate devise:views -e haml

If you see the following error when running the command:

Required dependency ruby_parser not found!
    Run "gem install ruby_parser" to get it.
Required dependency hpricot not found!
    Run "gem install hpricot" to get it.

make sure you have the following dependencies in Gemfile:

group :development do
  gem 'hpricot'
  gem 'ruby_parser'

Localizing URLs and Rails3 routes

Tagged i18n, routes, rails3, url, seo  Languages ruby

If you need to support localized URLs in a Rails application, you have at least two plugins to choose from: * i18n_routing NOTE: doesn't seem to work with Rails 3.2.8 * rails-translate-routes

I recommend the rails-translate-routes plugin because it allows me to create exactly the URLs I need.

For example, if these are the localized URLs I need:


How to use Rack::Cache with Rails 3

Tagged rack::cache, rails3, rails  Languages ruby

In Gemfile:

# Rails 3 includes rack-cache, so this is not needed.
gem 'rack-cache'

In config/environments/production.rb:

config.action_dispatch.rack_cache = {
    :metastore => "file:tmp/rack-cache/meta",
    :entitystore => "file:tmp/rack-cache/body",
    :verbose => true, # print debug information to log
    :allow_reload     => false, # allow user to force reload?
    :allow_revalidate => false, # allow user to force reload?
    :private_headers  => ['Cookie', 'Set-Cookie', 'Authorization'], # don't store these in the cache!
    :cache_key  =>  lambda { |request|
      Rack::Cache::Key.new(request).generate + ":jebus"
    }, # customize the cache key to make boss happy
    #:metastore   => 'memcached://localhost:11211/meta',
    #:entitystore   => 'memcached://localhost:11211/body'

In app/controllers/application_controller.rb:

class ApplicationController < ActionController::Base
  def cache_for(ttl = 5.minutes)
    response.headers['Vary'] = 'Accept' # We want to cache JSON and HTML separately! NOTE this header varies between browsers, so not optimal...
    expires_in(ttl, :public => true) unless signed_in? # We don't want to cache content if user is signed in!

Now you can cache all you want:

def index
  @data = BigData.all

Reference: * Rack::Cache on Github * Vary Header for RESTful Applications