File size: 1,361 Bytes
5010ad7
 
 
 
 
 
 
 
5d27770
5010ad7
 
 
 
 
 
 
 
 
 
 
 
5d27770
 
 
 
 
 
 
 
 
 
 
5010ad7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class ApplicationController < ActionController::Base
  include Pundit::Authorization
  include Pagy::Method

  allow_browser versions: :modern
  stale_when_importmap_changes

  before_action :set_locale
  before_action :set_paper_trail_whodunnit
  before_action :authenticate_user!, unless: :devise_or_static_controller?

  rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized

  layout :resolve_layout

  def default_url_options
    { locale: I18n.locale }
  end

  private

  def user_for_paper_trail
    current_user&.id&.to_s
  end

  def info_for_paper_trail
    {
      request_ip: request.remote_ip,
      request_path: request.path
    }
  end

  def devise_or_static_controller?
    is_a?(DeviseController) || is_a?(StaticController)
  end

  def resolve_layout
    is_a?(DeviseController) ? "devise" : "application"
  end

  def set_locale
    locale = params[:locale] || session[:locale] || I18n.default_locale
    locale = locale.to_sym if locale.is_a?(String)
    I18n.locale = I18n.available_locales.include?(locale) ? locale : I18n.default_locale
    session[:locale] = I18n.locale if params[:locale].present?
  end

  def user_not_authorized
    flash[:alert] = t("errors.not_authorized")
    redirect_back(fallback_location: root_path_with_locale)
  end

  def root_path_with_locale
    localized_root_path(I18n.locale)
  end
end