Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ncri
Created December 5, 2011 21:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ncri/1435458 to your computer and use it in GitHub Desktop.
Save ncri/1435458 to your computer and use it in GitHub Desktop.
# ---------------------------------------
# Helpers for creating translated routes
# ---------------------------------------
module RouteTranslation
BASE_LOCALES = [:de, :'de-CH']
URL_PREFIX_LOCALES = [:'fr-CH']
LOCALES = [BASE_LOCALES, URL_PREFIX_LOCALES].flatten
ROUTE_HELPER_CONTAINER = [
ActionController::Base,
ActionView::Base,
ActionMailer::Base,
ActionDispatch::Routing::UrlFor,
ActionController::TestCase
].freeze
def translated_named_route route_name, to
LOCALES.each do |locale|
base_locale = BASE_LOCALES.include?(locale)
path = "#{base_locale ? nil : locale}/#{I18n.t("routes.#{route_name}", locale: locale)}"
as = "#{route_name}#{"_#{locale.to_s.downcase.sub('-','_')}"}"
match path => to, as: as, locale: locale
end
RouteTranslation.add_untranslated_helpers_to_controllers_and_views(route_name)
end
private
# Taken (and slightly modified) from translate_routes gem: https://github.com/raul/translate_routes
#
# Add standard route helpers for default locale e.g.
# I18n.locale = :de
# people_path -> people_de_path
# I18n.locale = :fr
# people_path -> people_fr_path
#
def self.add_untranslated_helpers_to_controllers_and_views old_name
['path', 'url'].map do |suffix|
new_helper_name = "#{old_name}_#{suffix}"
ROUTE_HELPER_CONTAINER.each do |helper_container|
helper_container.send :define_method, new_helper_name do |*args|
send "#{old_name}_#{I18n.locale.to_s.downcase.sub('-','_')}_#{suffix}", *args
end
end
# puts "Added #{new_helper_name} route helper."
new_helper_name.to_sym
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment