application_controller.rb 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #---
  2. # Excerpted from "Agile Web Development with Rails",
  3. # published by The Pragmatic Bookshelf.
  4. # Copyrights apply to this code. It may not be used to create training material,
  5. # courses, books, articles, and the like. Contact us if you are in doubt.
  6. # We make no guarantees that this code is fit for any purpose.
  7. # Visit http://www.pragmaticprogrammer.com/titles/rails4 for more book information.
  8. #---
  9. class ApplicationController < ActionController::Base
  10. before_filter :set_i18n_locale_from_params
  11. # ...
  12. before_filter :authorize
  13. protect_from_forgery
  14. private
  15. def current_cart
  16. Cart.find(session[:cart_id])
  17. rescue ActiveRecord::RecordNotFound
  18. cart = Cart.create
  19. session[:cart_id] = cart.id
  20. cart
  21. end
  22. # ...
  23. protected
  24. def authorize
  25. if request.format == Mime::HTML
  26. unless User.find_by_id(session[:user_id])
  27. redirect_to login_url, notice: "Please log in"
  28. end
  29. else
  30. authenticate_or_request_with_http_basic do |username, password|
  31. user = User.find_by_name(username)
  32. user && user.authenticate(password)
  33. end
  34. end
  35. end
  36. def set_i18n_locale_from_params
  37. if params[:locale]
  38. if I18n.available_locales.include?(params[:locale].to_sym)
  39. I18n.locale = params[:locale]
  40. else
  41. flash.now[:notice] =
  42. "#{params[:locale]} translation not available"
  43. logger.error flash.now[:notice]
  44. end
  45. end
  46. end
  47. def default_url_options
  48. { locale: I18n.locale }
  49. end
  50. end