Last active
December 9, 2016 17:21
-
-
Save genaromadrid/3ca890233f9c46cdf09b655133e5dadd to your computer and use it in GitHub Desktop.
A really small library to translate routes for better SEO
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class RouteTranslator | |
def self.routes(rails_router, &block) | |
RouteTranslator.new(rails_router).instance_eval(&block) | |
end | |
def initialize(rails_router) | |
@rails_router = rails_router | |
end | |
def get(route, options) | |
redirect = options.key?(:redirect) ? options[:redirect] : true | |
options.delete(:redirect) | |
I18n.available_locales.each do |loc| | |
rails_router.scope loc, defaults: { locale: loc } do | |
rails_router.get(translate_route(route, loc), options.merge(as: "#{options[:as] || route}_#{loc}")) | |
end | |
end | |
return unless redirect | |
I18n.available_locales.each do |loc| | |
translated = translate_route(route, loc) | |
rails_router.get(translated, to: rails_router.redirect("#{loc}/#{translated}")) | |
end | |
end | |
private | |
attr_reader :rails_router | |
def translate_route(route, locale) | |
path = "routes.#{route}" | |
unless I18n.exists?(path, locale) | |
fail "you need to define '#{locale}::routes::#{route}' in your 'routes.yml'" | |
end | |
I18n.t(path, locale: locale) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Acording to SEO best practices you should translate the URLs for multilingual sites. To do that in rails you have to add a lot of lines to your
routes.rb
. For example if you have prices and questions in two languages you'd have something like this:This library allows you to do the exact same thing with 4 lines of code in your
routes.rb
and some in yourconfig/locales
folder:Which will generate:
That's it