Skip to content

Instantly share code, notes, and snippets.

@petyosi
Created December 12, 2008 10:51
Show Gist options
  • Save petyosi/35076 to your computer and use it in GitHub Desktop.
Save petyosi/35076 to your computer and use it in GitHub Desktop.
# Include hook code here
class ActionController::Routing::RouteSet::Mapper
def languages(*options)
$LANGUAGES = options.map &:to_s # ugly. Any other idea?
end
end
# Brutal hack, in the guts. May not work with any other version.
class ActionController::Routing::RouteSet
alias :old_write_recognize_optimized :write_recognize_optimized
def write_recognize_optimized
tree = segment_tree(routes)
body = generate_code(tree)
instance_eval %{
def recognize_optimized(path, env)
segments = to_plain_segments(path)
if $LANGUAGES.include? segments.first
language = segments.shift
path.sub!(Regexp.new('^/' + language), '')
end
index = #{body}
return nil unless index
while index < routes.size
result = routes[index].recognize(path, env) and return result.merge({:lang => language})
index += 1
end
nil
end
}, __FILE__, __LINE__
end
end
class ActionController::Base
alias :old_url_for :url_for
def url_for(options = nil)
q = old_url_for options
if params[:lang]
q.sub! /\w(\/)|^(\/)/, '\0' + params[:lang] + '/'
end
q
end
def self.requires_language
class_eval do
helper_method :lang
def lang
params[:lang] && params[:lang].to_sym
end
before_filter :detect_language
def detect_language
redirect_to root_url + preferred_language if lang.blank?
end
end
end
protected
def preferred_language
$LANGUAGES.find {|l| request.env["HTTP_ACCEPT_LANGUAGE"].include?(l)} or $LANGUAGES.first
end
end
# Sorry for this. not sure how will affect the perf.
module ActionController::Routing::Optimisation
def generate_optimisation_block(route, kind)
""
end
end
module LanguageHelper
# Works for two languags, change the title with gettext.
def language_switch_link(label)
the_other = $LANGUAGES.find {|l| l != lang.to_s}
link_to label, root_url.sub(lang.to_s, the_other.to_s)
end
def M_(instance, field = 'name')
#not in language context
return instance.send(field) unless self.respond_to?(:lang)
if instance.respond_to? "#{lang}_#{field}"
instance.send("#{lang}_#{field}")
elsif instance.respond_to? field
instance.send field
else
raise "#{instance.class} can't be properly language converted"
end
end
end
ActionView::Base.class_eval { include LanguageHelper }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment