Rails I18n and 404/500 Error Pages

If you have a multilingual site it makes sense for your 404 and 500 error pages to be multilingual as well. Rails supports multilinguality by serving up error pages with a path like public/500.sv.html, where sv is the locale. In the case where Rails itself is fundamentally broken or fails to respond your webserver will respond with public/500.html, so we need that file as well. A way to achieve this is to keep your 404 and 500 pages as ERB templates with I18n.translate lookups under app/views/errors and have a Rake task that generates the static files under public:

That Rake task can then be invoked by Capistrano in an after_update_code deploy hook to make the pages available in production.

Posted by peter Posted in Ruby on Rails, Services
  • http://github.com/grimen grimen

    This is what I did:

    http://pastie.org/783449

    …enabled with:

    class ApplicationController < ActionController::Base
    inlcude Application::ErrorFilters
    end

    I guess my solution won’t work for non-Rails-triggered 500 errors (haven’t tested) when page-caching is not used, but haven’t tested that yet.

  • http://twitter.com/bolsanova bolsanova

    Is this solution suppose to render any layout as well?  Another question, which is the purpose of the with_locale method?

    Thanks for sharing.

  • http://twitter.com/bolsanova bolsanova

     Is thi

  • Anonymous

    Is this solution suppose to render any layout as well?  Another question, which is the purpose of the with_locale method?Thanks for sharing.

  • http://twitter.com/martinsvalin Martin Svalin

    Hi,
    The rake task doesn’t use Rails’ render method, and doesn’t render layouts. It just interprets the ERB files you provide in app/views/errors/.

    The I18n.with_locale method lets you run a block without changing your I18n.locale. It temporarily sets the locale, runs the block, and resets the locale. I use it often at the Rails console, to quickly look at the result of some code under different locales. Or to set translated attributes in AR: 
    I18n.with_locale(:en) { Category.find(1).update_attribute :name, “Name in English” }
    I18n.with_locale(:sv) { Category.find(1).update_attribute :name, “Namn på svenska” }

    Very useful.

  • Anonymous

    Thank you for your quick answer :)

blog comments powered by Disqus