application_controller.rb 1.9 KB

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