/api/app/controllers/spree/api/resource_controller.rb

https://github.com/solidusio/solidus · Ruby · 87 lines · 67 code · 19 blank · 1 comment · 4 complexity · c6ee3db27732060438a7a421f100204d MD5 · raw file

  1. # frozen_string_literal: true
  2. class Spree::Api::ResourceController < Spree::Api::BaseController
  3. before_action :load_resource, only: [:show, :update, :destroy]
  4. def index
  5. collection_scope = model_class.accessible_by(current_ability)
  6. if params[:ids]
  7. ids = params[:ids].split(",").flatten
  8. collection_scope = collection_scope.where(id: ids)
  9. else
  10. collection_scope = collection_scope.ransack(params[:q]).result
  11. end
  12. @collection = paginate(collection_scope)
  13. instance_variable_set("@#{controller_name}", @collection)
  14. respond_with(@collection)
  15. end
  16. def show
  17. respond_with(@object)
  18. end
  19. def new
  20. authorize! :new, model_class
  21. respond_with(model_class.new)
  22. end
  23. def create
  24. authorize! :create, model_class
  25. @object = model_class.new(permitted_resource_params)
  26. instance_variable_set("@#{object_name}", @object)
  27. if @object.save
  28. respond_with(@object, status: 201, default_template: :show)
  29. else
  30. invalid_resource!(@object)
  31. end
  32. end
  33. def update
  34. authorize! :update, @object
  35. if @object.update(permitted_resource_params)
  36. respond_with(@object, status: 200, default_template: :show)
  37. else
  38. invalid_resource!(@object)
  39. end
  40. end
  41. def destroy
  42. authorize! :destroy, @object
  43. if @object.destroy
  44. respond_with(@object, status: 204)
  45. else
  46. invalid_resource!(@object)
  47. end
  48. rescue ActiveRecord::DeleteRestrictionError
  49. render "spree/api/errors/delete_restriction", status: 422
  50. end
  51. protected
  52. def load_resource
  53. @object = model_class.accessible_by(current_ability, :show).find(params[:id])
  54. instance_variable_set("@#{object_name}", @object)
  55. end
  56. def permitted_resource_params
  57. params.require(object_name).permit(permitted_resource_attributes)
  58. end
  59. def permitted_resource_attributes
  60. send("permitted_#{object_name}_attributes")
  61. end
  62. def model_class
  63. "Spree::#{controller_name.classify}".constantize
  64. end
  65. def object_name
  66. controller_name.singularize
  67. end
  68. end