Skip to content

Instantly share code, notes, and snippets.

@munkius
Created October 27, 2013 19:06
Show Gist options
  • Save munkius/7186580 to your computer and use it in GitHub Desktop.
Save munkius/7186580 to your computer and use it in GitHub Desktop.
This Rails module takes locales into account when rendering a link to the current path. It takes into consideration all parameters. This is useful when you want a user to be able to switch languages and you want the user to stay on the same URL. When passing the default locale, it will be stripped off. For other details, take a look at the spec.
module PathHelper
class LocaleUtil
def delocalize_url(url)
result = url.sub(/^\/(?:#{locales_in_correct_order.join('|')})/, '')
[result, '/'].reject(&:blank?).first
end
def locales_in_correct_order
I18n.available_locales.map(&:to_s).sort_by(&:length).reverse
end
end
def current_path(options={})
locale = options[:locale]
r = request.env['ORIGINAL_FULLPATH']
r = LocaleUtil.new.delocalize_url(r)
if locale.blank? || locale == I18n.default_locale
r
else
"/#{locale}#{r}"
end
end
end
require "spec_helper"
describe PathHelper do
include PathHelper
it "does not add a locale to the URL when not passing any" do
@path = "/gigs"
I18n.available_locales.each do |locale|
I18n.default_locale = locale
current_path.should eq @path
end
end
it "returns a URL based on the given locale" do
@path = "/gigs"
I18n.available_locales.each do |locale|
I18n.default_locale = I18n.available_locales.reject{|l| l == locale}.sample
current_path(locale: locale).should eq "/#{locale}#{@path}"
end
end
it "should blank the locale when passed locale is same as default" do
@path = "/gigs"
I18n.default_locale = :nl
current_path(locale: :nl).should eq @path
end
it "returns a localized URL and strip off a previous locale" do
locales = I18n.available_locales
locales_without_default = locales.reject{|l| l == I18n.default_locale}
locales.each do |current_locale|
locales_without_default.each do |locale|
@path = "/#{current_locale}/gigs"
current_path(locale: locale).should eq("/#{locale}/gigs")
end
end
end
it "delocalizes URLs" do
locale_util = PathHelper::LocaleUtil.new
locale_util.delocalize_url("/").should eq "/"
locale_util.delocalize_url("/gigs").should eq "/gigs"
I18n.available_locales.each do |locale|
locale_util.delocalize_url("/#{locale}/gigs").should eq "/gigs"
locale_util.delocalize_url("/#{locale}/").should eq "/"
locale_util.delocalize_url("/#{locale}").should eq "/"
end
end
def request
stub(env: {'ORIGINAL_FULLPATH' => @path})
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment