Skip to content

Instantly share code, notes, and snippets.

@tkfm-yamaguchi
Last active August 29, 2015 13:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tkfm-yamaguchi/9110498 to your computer and use it in GitHub Desktop.
Save tkfm-yamaguchi/9110498 to your computer and use it in GitHub Desktop.
This lets middleman's `url_for` see the locale parameter even if `relative_url` option is true.
# coding: utf-8
module MiddlemanExt
module Util
def self.included(base)
base.send :include, ClassMethods
base.send :alias_method, :url_for_without_locale, :url_for
base.send :alias_method, :url_for, :url_for_with_locale
end
module ClassMethods
# NOTE: This assumes:
# - set relative_links true
# - activate :relative_assets
def url_for_with_locale(app, path_or_resource, options={})
_opt = options
_opt.symbolize_keys!
# To set locale manually, remove the key from options
locale = _opt.delete(:locale) || I18n.locale.intern
# Handle Resources and other things which define their own url method
# (* borrowed from middleman)
url = path_or_resource.respond_to?(:path) ? "/#{path_or_resource.path}" : path_or_resource
url = url.gsub(' ', '%20')
# Locale prepend target is which begins '/',
# because if a relative path was specified,
# its locale should be prepended to current_page.url
# NOTICE:
# In cases below also are not concerened:
# - if url is made from the only fragment.
# - if url includes the protocol prefix.
if url =~ /^\//
# If it is requested default locale,
# locale prefix for url is blank.
if I18n.default_locale == locale
# If current locale is not the default locale
unless I18n.locale == I18n.default_locale
# url might have a prefix of current locale,
# so it should be take away.
url.sub!(/^\/#{I18n.locale}/, '')
end
# If current locale is default locale,
# url might not have locale prefix.
# ( is that so ?)
else
# requested locale is not a default locale,
# so we should append the locale prefix to the url,
# if it does not have.
if url !~ /^\/#{locale}/
url = "/#{locale}#{url}"
end
end
end
url_for_without_locale(app, url, _opt)
end
end
end
end
module Middleman
module Util
class << self
include MiddlemanExt::Util
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment