Never been to TextSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

« Newer Snippets
Older Snippets »
3 total  XML / RSS feed 

globalize error_messages_for on edge rails

if you're like me and use globalize and edge rails, there's a problem with error_messages_for giving away blank pages or nils.

here's the solution, open /vendor/plugins/globalize/lib/globalize/rails/active_record_helper.rb and copy/paste this code:

module ActionView
  module Helpers
    module ActiveRecordHelper
      # Returns a string with a div containing all of the error messages for the objects located as instance variables by the names
      # given.  If more than one object is specified, the errors for the objects are displayed in the order that the object names are
      # provided.
      #
      # This div can be tailored by the following options:
      #
      # * header_tag - Used for the header of the error div (default: h2)
      # * id - The id of the error div (default: errorExplanation)
      # * class - The class of the error div (default: errorExplanation)
      # * object_name - The object name to use in the header, or
      # any text that you prefer. If object_name is not set, the name of
      # the first object will be used.
      #
      # Specifying one object:
      # 
      #   error_messages_for 'user'
      #
      # Specifying more than one object (and using the name 'user' in the
      # header as the object_name instead of 'user_common'):
      #
      #   error_messages_for 'user_common', 'user', :object_name => 'user'
      #
      # NOTE: This is a pre-packaged presentation of the errors with embedded strings and a certain HTML structure. If what
      # you need is significantly different from the default presentation, it makes plenty of sense to access the object.errors
      # instance yourself and set it up. View the source of this method to see how easy it is.
      #
      # Adapted for Globalize Edge Rails by Claudio Poli ([email protected])
      def error_messages_for(*params)
        options = params.last.is_a?(Hash) ? params.pop.symbolize_keys : {}
        objects = params.collect {|object_name| instance_variable_get("@#{object_name}") }.compact
        count   = objects.inject(0) {|sum, object| sum + object.errors.count }
        unless count.zero?
          html = {}
          [:id, :class].each do |key|
            if options.include?(key)
              value = options[key]
              html[key] = value unless value.blank?
            else
              html[key] = 'errorExplanation'
            end
          end
          header_message = "#{pluralize(count, 'error')} prohibited this #{(options[:object_name] || params.first).to_s.gsub('_', ' ').t} from being saved"
          error_messages = objects.map {|object| object.errors.full_messages.map {|msg| content_tag(:li, msg) } }
          content_tag(:div,
            content_tag(options[:header_tag] || :h2, header_message) <<
              content_tag(:p, 'There were problems with the following fields:'.t) <<
              content_tag(:ul, error_messages),
            html
          )
        else
          ''
        end
      end
    end
  end
end

Setting Globalize locale based on the Accept-Language HTTP Header Field

This code sets the Globalize locale based on the http accept-language header field. Other options are also considered, in order or precedence:

- Explicetely locale set on URL
- Previous language selection (stored on user session)
- Accept-Language field contents
- Default locale

  before_filter :set_locale
  
  def set_locale
    default_locale = 'en-US'
    request_language = request.env['HTTP_ACCEPT_LANGUAGE']
    request_language = request_language.nil? ? nil : request_language[/[^,;]+/]
    
    @locale = params[:locale] || session[:locale] ||
              request_language || default_locale
    session[:locale] = @locale
    begin
      Locale.set @locale
    rescue
      @locale = default_locale
      Locale.set @locale
    end
    
  end

Setup Globalize plugin in Rails

Don't forget to edit config/database.yml first.

Terminal:
script/plugin install \
    http://svn.globalize-rails.org/svn/globalize/globalize/trunk 
rake globalize:setup 


…in config/environment.rb:
include Globalize
Locale.set_base_language 'en-US'


…in the app controller, before any other filter:
  before_filter :set_locale
  # FIXME, NOT TESTED YET, PROBABLY DOESN'T WORK.
  def set_locale
    if params[:locale]
      # The user has explicitly requested a locale.
      session[:locale] = params[:locale]
      Locale.set params[:locale]
    elsif session[:locale].empty?
      # The user has a current session.
      Locale.set session[:locale]
    elsif ! request.env["HTTP_ACCEPT_LANGUAGE"].empty?
      # We use the browser's locale settings.
      Locale.set request.env["HTTP_ACCEPT_LANGUAGE"][/[a-z]{2}-[a-z]{2}/i]
    else
      # the default locale defined in config/environment.rb is used.
    end
  end


…in the model:
class Blog < ActiveRecord::Base
  translates :title, :post
end
« Newer Snippets
Older Snippets »
3 total  XML / RSS feed