Module | ActionController::Filters::ClassMethods |
In: |
lib/gloc-rails.rb
|
This filter attempts to auto-detect the clients desired language. It first checks the params, then a cookie and then the HTTP_ACCEPT_LANGUAGE request header. If a language is found to match or be similar to a currently valid language, then it sets the current_language of the controller.
class ExampleController < ApplicationController set_language :en autodetect_language_filter :except => 'monkey', :on_no_lang => :lang_not_autodetected_callback autodetect_language_filter :only => 'monkey', :check_cookie => 'monkey_lang', :check_accept_header => false ... def lang_not_autodetected_callback redirect_to somewhere end end
The args for this filter are exactly the same the arguments of before_filter with the following exceptions:
You override the default names of the param or cookie by calling GLoc.set_config :default_param_name => ‘new_param_name‘ and GLoc.set_config :default_cookie_name => ‘new_cookie_name‘.
# File lib/gloc-rails.rb, line 43 43: def autodetect_language_filter(*args) 44: options= args.last.is_a?(Hash) ? args.last : {} 45: x= 'Proc.new { |c| l= nil;' 46: # :check_params 47: unless (v= options.delete(:check_params)) == false 48: name= v ? ":#{v}" : 'GLoc.get_config(:default_param_name)' 49: x << "l ||= GLoc.similar_language(c.params[#{name}]);" 50: end 51: # :check_cookie 52: unless (v= options.delete(:check_cookie)) == false 53: name= v ? ":#{v}" : 'GLoc.get_config(:default_cookie_name)' 54: x << "l ||= GLoc.similar_language(c.send(:cookies)[#{name}]);" 55: end 56: # :check_accept_header 57: unless options.delete(:check_accept_header) == false 58: x << %< 59: unless l 60: a= c.request.env['HTTP_ACCEPT_LANGUAGE'].split(/,|;/) rescue nil 61: a.each {|x| l ||= GLoc.similar_language(x)} if a 62: end; > 63: end 64: # Set language 65: x << 'ret= true;' 66: x << 'if l; c.set_language(l); c.headers[\'Content-Language\']= l.to_s; ' 67: if options.has_key?(:on_set_lang) 68: x << "ret= c.#{options.delete(:on_set_lang)}(l);" 69: end 70: if options.has_key?(:on_no_lang) 71: x << "else; ret= c.#{options.delete(:on_no_lang)};" 72: end 73: x << 'end; ret }' 74: 75: # Create filter 76: block= eval x 77: before_filter(*args, &block) 78: end