You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
2.0 KiB

8 years ago
7 years ago
7 years ago
7 years ago
8 years ago
  1. # frozen_string_literal: true
  2. class ApplicationController < ActionController::Base
  3. # Prevent CSRF attacks by raising an exception.
  4. # For APIs, you may want to use :null_session instead.
  5. protect_from_forgery with: :exception
  6. force_ssl if: "Rails.env.production? && ENV['LOCAL_HTTPS'] == 'true'"
  7. helper_method :current_account
  8. rescue_from ActionController::RoutingError, with: :not_found
  9. rescue_from ActiveRecord::RecordNotFound, with: :not_found
  10. before_action :store_current_location, except: :raise_not_found, unless: :devise_controller?
  11. before_action :set_locale
  12. before_action :set_user_activity
  13. def raise_not_found
  14. raise ActionController::RoutingError, "No route matches #{params[:unmatched_route]}"
  15. end
  16. private
  17. def store_current_location
  18. store_location_for(:user, request.url)
  19. end
  20. def set_locale
  21. I18n.locale = current_user.try(:locale) || I18n.default_locale
  22. rescue I18n::InvalidLocale
  23. I18n.locale = I18n.default_locale
  24. end
  25. def require_admin!
  26. redirect_to root_path unless current_user&.admin?
  27. end
  28. def set_user_activity
  29. current_user.touch(:current_sign_in_at) if !current_user.nil? && current_user.current_sign_in_at < 24.hours.ago
  30. end
  31. protected
  32. def not_found
  33. respond_to do |format|
  34. format.any { head 404 }
  35. end
  36. end
  37. def gone
  38. respond_to do |format|
  39. format.any { head 410 }
  40. end
  41. end
  42. def current_account
  43. @current_account ||= current_user.try(:account)
  44. end
  45. def cache_collection(raw, klass)
  46. uncached_ids = []
  47. cached_keys_with_value = Rails.cache.read_multi(*raw.map(&:cache_key))
  48. raw.each do |item|
  49. uncached_ids << item.id unless cached_keys_with_value.key?(item.cache_key)
  50. end
  51. unless uncached_ids.empty?
  52. uncached = klass.where(id: uncached_ids).with_includes.map { |item| [item.id, item] }.to_h
  53. uncached.values.each do |item|
  54. Rails.cache.write(item.cache_key, item)
  55. end
  56. end
  57. raw.map { |item| cached_keys_with_value[item.cache_key] || uncached[item.id] }.compact
  58. end
  59. end