ca1989

ca1989

Ex_cldr - need to call Gettext.put_locale to make it work

Hi all,

my backend module looks like:

defmodule OHA.Cldr do
  @moduledoc false

  @gettext_module Application.compile_env(:oha, :gettext, OHA.Gettext)

  use Cldr,
    locales: ["en", "de"],
    default_locale: "de",
    gettext: @gettext_module,
    data_dir: "./priv/cldr",
    otp_app: :oha,
    precompile_number_formats: ["¤¤#,##0.##"],
    providers: [
      Cldr.Number,
      Cldr.List,
      Cldr.Unit,
      Cldr.Territory,
      Cldr.DateTime,
      Cldr.LocaleDisplay
    ],
    generate_docs: false,
    force_locale_download: false
end

then I have a Phoenix project that uses that backend. The conf where I set the gettext_module looks like this:

config :oha, gettext: ZdbWeb.Gettext

Then I have the plugs for both the conn and the session in my browser pipeline, as I use both dead and live views:

pipeline :browser do
  plug(:accepts, ["html"])
  plug(:fetch_session)

  plug Cldr.Plug.PutLocale,
    apps: [:cldr, :gettext],
    from: [:query, :session, :path, :body, :cookie, :accept_language],
    param: "l",
    gettext: ZdbWeb.Gettext,
    cldr: OHA.Cldr

  plug Cldr.Plug.PutSession, as: :string
  plug(:fetch_live_flash)
  plug(:protect_from_forgery)
  plug(:put_secure_browser_headers)
  plug(:fetch_current_user)
end

Then I have a mount hook where I set the locale from what I have in the params or the session:

defmodule OHAWeb.RestoreLocale do
  def on_mount(:default, %{"l" => locale}, _session, socket) do
    # Gettext.put_locale(locale)
    OHA.Cldr.put_locale(locale)
    {:cont, socket}
  end

  def on_mount(:default, _params, %{"cldr_locale" => locale}, socket) do
    # Gettext.put_locale(locale)
    OHA.Cldr.put_locale(locale)
    {:cont, socket}
  end

  def on_mount(:default, _params, _session, socket), do: {:cont, socket}
end

This code does not work, I have to manually call Gettect.put_locale(locale) to make it work.

I am doing something wrong for sure, ideas?

Thank you
Cheers!

Marked As Solved

kip

kip

ex_cldr Core Team

Its a good question @ca1989 and it reflects the different environments between the initial HTTP request handled by Cldr.Plug.PutLocale and what happens when the live view is mounted.

The locale set by Cldr.put_locale/1 and Gettext.put_locale/1 are stored in the Process Dictionary which, by definition, is per-process. In the initial HTTP request, Cldr.Plug.PutLocale takes care of this based upon the plug configuration. Since you have configured the plug to set both locales, it does that.

Since each live view is a separate process, Cldr.put_locale/1 and Gettext.put_locale/1 need to be called again in the mount - exactly as you are doing.

Your question might be “why doesn’t Cldr.put_locale/1 also call Gettext.put_locale/1”? My reasoning has been that it would be a little bit too “magic” and that being explicit is better than implicit.

Also Liked

kip

kip

ex_cldr Core Team

Good question - I was a bit brief and inaccurate in my answer. The function Cldr.put_gettext_locale/1 takes care of using the LanguageTag to set the Gettext locale appropriately.

I think the right pattern here would be:

def on_mount(:default, _params, %{"cldr_locale" => locale}, socket) do
  Cldr.put_gettext_locale(locale)
  OHA.Cldr.put_locale(locale)
  {:cont, socket}
end

Cldr.put_gettext_locale/1 takes a CLDR locale, extracts the gettext_locale_name field and uses it with Gettext.put_locale/1. Its implementation is very simple:

@spec put_gettext_locale(LanguageTag.t()) :: {:ok, binary() | nil} | {:error, {module(), String.t()}}

def put_gettext_locale(%LanguageTag{gettext_locale_name: nil} = locale) do
  {:error,
    {Cldr.UnknownLocaleError,
      "Locale #{inspect(locale)} does not map to a known gettext locale name"}}
end

def put_gettext_locale(%LanguageTag{gettext_locale_name: gettext_locale_name} = locale) do
  gettext_backend = locale.backend.__cldr__(:gettext)
  _ = Gettext.put_locale(gettext_backend, gettext_locale_name)
  {:ok, gettext_locale_name}
end

In preparing this response I can see that generating a function OHA.Cldr.put_gettext_locale/1 in the CLDR backend would be more consistent and I have pushed a commit to do just that..

Where Next?

Popular in Questions Top

chokchit
** (DBConnection.ConnectionError) connection not available and request was dropped from queue after 2733ms. You can configure how long re...
New
New
Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&query=perfume&page=2, I would like to get: ...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
JulienCorb
I am trying to implement my new.html.eex file to create new posts on my website. new.html.eex: <h1>Create Post</h1> <%= ...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: The documentation above suggests that while ...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New

Other popular topics Top

hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a > b) do {:ok, "a"} end if (a < b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement