Paulo Janeiro
Paulo Janeiro

Reputation: 3211

How to access 'conn' in the Controller module outside an action

I want to be able to define a variable that needs to access to conn in my controller module but outside any action so that I can use it in any action:

defmodule Skeleton.Web.PageController do
  use Skeleton.Web, :controller
  locale = conn |> get_session(:locale)

  def news(conn, _params) do
    render(conn, "news.html", locale: locale)"
  end
end

How to access it?

Upvotes: 1

Views: 250

Answers (1)

Dogbert
Dogbert

Reputation: 222138

You can't. The code in the module is evaluated once at compilation. conn is a unique value that's created for each request and passed to the action.

You can override the action/2 function to extract and pass the locale to each action:

def action(conn, _) do
  args = [conn, conn.params, get_session(conn, :locale)]
  apply(__MODULE__, action_name(conn), args)
end

Source

Now each action in the controller will get 3 arguments, conn, params, and locale:

def news(conn, _params, locale) do
  render(conn, "news.html", locale: locale)"
end

You can also create a helper function but the code would not be much shorter in this case as you'll have to explicitly pass conn to it:

def news(conn, _params) do
  render(conn, "news.html", locale: locale(conn))"
end

def locale(conn), do: get_session(conn, :locale)

Upvotes: 1

Related Questions