Skip to content

Instantly share code, notes, and snippets.

@alexedwards
Created March 18, 2018 20:03
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 alexedwards/eedfeae0528d2d061b90ac5d6d470352 to your computer and use it in GitHub Desktop.
Save alexedwards/eedfeae0528d2d061b90ac5d6d470352 to your computer and use it in GitHub Desktop.
I18n for Sinatra
configure do
enable :protection
set :sessions, key: "session", expire_after: 25920000, path: "/"
set :session_secret, ENV["SESSION_SECRET"]
helpers Sinatra::Helpers
use Rack::Flash
use Rack::Protection::AuthenticityToken
I18n.load_path = ["./blog/locales/en.yml", "./blog/locales/de.yml"]
end
before "/" do
locale = I18n.locale_from_header(request.env["HTTP_ACCEPT_LANGUAGE"])
redirect to("/#{locale}/"), 302
end
before "/:locale/*" do
locale = params[:locale].to_sym
halt 404 unless I18n.available_locales.include?(locale)
I18n.locale = locale
request.path_info = "/#{params[:splat][0]}"
end
<html lang="<%= I18n.locale %>">
...
<h1><%= I18n.t(:all_posts) %></h1>
module I18n
module Base
# TODO: Need to test this properly. What happens if blank? Not supported locale?
# BETTER: use Rack::Locale instead...
def locale_from_header(header)
locale = header.scan(/^[a-z]{2}/).first.to_sym
available_locales.include?(locale) ? locale : default_locale
end
def format_number(number)
thousands_separator = t("numbers.thousand_separator") || ","
decimal_separator = t("numbers.decimal_separator") || "."
left, right = number.to_s.split(".")
left.gsub!(/(\d)(?=(\d\d\d)+(?!\d))/) do |digit_to_delimit|
"#{digit_to_delimit}#{thousands_separator}"
end
[left, right].compact.join(decimal_separator)
end
# Prefix a url with the current locale
# Example: "/orders/show/1" becomes "/de/orders/show/1"
def link(url, text)
%{<a href="/#{locale}#{url}">#{t text}</a>}
end
def url(url)
"/#{locale}#{url}"
end
end
end
de:
all_posts: "Alle Beiträge"
new: "Neu"
numbers:
thousand_separator: "."
decimal_separator: ","
en:
all_posts: "All Posts"
new: "New"
numbers:
thousand_separator: ","
decimal_separator: "."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment