# lib/my_app_web/plugs/growthbook_plug.ex
defmodule MyAppWeb.GrowthBookPlug do
import Plug.Conn
def init(opts), do: opts
def call(conn, _opts) do
# Build user attributes from session/assigns
user = conn.assigns[:current_user]
attributes = %{
"id" => user_id(user),
"email" => user && user.email,
"country" => get_country_from_ip(conn.remote_ip),
"user_agent" => get_req_header(conn, "user-agent") |> List.first(),
"url" => conn.request_path,
"plan" => user && user.subscription_plan
}
# Create GrowthBook context
context = GrowthBook.build_context(attributes)
# Store context in conn.assigns for use in controllers/views
assign(conn, :growthbook, context)
end
defp user_id(nil), do: nil
defp user_id(user), do: to_string(user.id)
defp get_country_from_ip(_ip) do
# Implement IP geolocation
"US"
end
end
# lib/my_app_web/router.ex
defmodule MyAppWeb.Router do
use MyAppWeb, :router
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_live_flash
plug :put_root_layout, {MyAppWeb.LayoutView, :root}
plug :protect_from_forgery
plug :put_secure_browser_headers
plug :fetch_current_user
plug MyAppWeb.GrowthBookPlug # Add GrowthBook plug
end
# Your routes...
end
# lib/my_app_web/controllers/dashboard_controller.ex
defmodule MyAppWeb.DashboardController do
use MyAppWeb, :controller
def index(conn, _params) do
# Access GrowthBook context from conn.assigns
gb = conn.assigns.growthbook
# Use feature flags to control UI
show_new_dashboard = GrowthBook.feature(gb, "new-dashboard").on?
max_items = GrowthBook.feature(gb, "dashboard-max-items").value || 10
# Track experiment if user is in one
color_result = GrowthBook.feature(gb, "dashboard-theme-color")
if color_result.source == :experiment do
track_experiment(conn, color_result.experiment, color_result.experiment_result)
end
render(conn, "index.html",
new_dashboard: show_new_dashboard,
max_items: max_items,
theme_color: color_result.value
)
end
defp track_experiment(conn, experiment, result) do
# Track to your analytics service
MyApp.Analytics.track(conn.assigns.current_user, "experiment_viewed", %{
experiment_id: experiment.key,
variation_id: result.variation_id
})
end
end