PageRenderTime 1527ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/app/controllers/admin/pictures_controller.rb

https://github.com/seaneshbaugh/portfolio
Ruby | 117 lines | 80 code | 34 blank | 3 comment | 2 complexity | f0ab399e37470c531f439cd6800a8655 MD5 | raw file
  1. # frozen_string_literal: true
  2. module Admin
  3. class PicturesController < AdminController
  4. def index
  5. authorize Picture
  6. @search = Picture.ransack(params[:q])
  7. @pictures = @search.result.page(params[:page]).per(25).reverse_chronological
  8. # TODO: Consider moving this to a proper API with some sort of token based authentication.
  9. respond_to do |format|
  10. format.html
  11. format.json do
  12. render json: @pictures.map { |picture| PictureSerializer.new(picture).as_json }
  13. end
  14. end
  15. end
  16. def show
  17. @picture = find_picture
  18. authorize @picture
  19. end
  20. def new
  21. authorize Picture
  22. @picture = Picture.new
  23. end
  24. def create
  25. authorize Picture
  26. @picture = Picture.new(picture_params)
  27. respond_to do |format|
  28. if @picture.save
  29. format.html do
  30. flash[:success] = t('.success')
  31. redirect_to admin_picture_url(@picture), status: :see_other
  32. end
  33. format.json do
  34. render json: PictureSerializer.new(@picture).as_json
  35. end
  36. else
  37. format.html do
  38. flash.now[:error] = helpers.error_messages_for(@picture)
  39. render 'new', status: :unprocessable_entity
  40. end
  41. format.json do
  42. # TODO: Maybe put this in a helper? See http://jsonapi.org/format/#error-objects.
  43. render json: { errors: @picture.errors.map { |attribute, message| { title: "#{attribute.to_s.humanize} #{message}" } } }
  44. end
  45. end
  46. end
  47. end
  48. def edit
  49. @picture = find_picture
  50. authorize @picture
  51. end
  52. def update
  53. @picture = find_picture
  54. authorize @picture
  55. if @picture.update(picture_params)
  56. flash[:success] = t('.success')
  57. redirect_to edit_admin_picture_url(@picture), status: :see_other
  58. else
  59. flash.now[:error] = helpers.error_messages_for(@picture)
  60. render 'edit', status: :unprocessable_entity
  61. end
  62. end
  63. def destroy
  64. @picture = find_picture
  65. authorize @picture
  66. @picture.destroy
  67. flash[:success] = t('.success')
  68. redirect_to admin_pictures_url, status: :see_other
  69. end
  70. def selector
  71. authorize Picture, :create
  72. @pictures = Picture.reverse_chronological
  73. render layout: false
  74. end
  75. private
  76. def find_picture
  77. Picture.friendly.find(params[:id])
  78. end
  79. def picture_params
  80. params.require(:picture).permit(:title, :alt_text, :caption, :image)
  81. end
  82. end
  83. end