/api/app/controllers/spree/api/variants_controller.rb

https://github.com/solidusio/solidus · Ruby · 90 lines · 71 code · 15 blank · 4 comment · 8 complexity · 49a52563cdd44ebf910e82777f13a14a MD5 · raw file

  1. # frozen_string_literal: true
  2. module Spree
  3. module Api
  4. class VariantsController < Spree::Api::BaseController
  5. before_action :product
  6. def create
  7. authorize! :create, Variant
  8. @variant = scope.new(variant_params)
  9. if @variant.save
  10. respond_with(@variant, status: 201, default_template: :show)
  11. else
  12. invalid_resource!(@variant)
  13. end
  14. end
  15. def destroy
  16. @variant = scope.accessible_by(current_ability, :destroy).find(params[:id])
  17. @variant.discard
  18. respond_with(@variant, status: 204)
  19. end
  20. # The lazyloaded associations here are pretty much attached to which nodes
  21. # we render on the view so we better update it any time a node is included
  22. # or removed from the views.
  23. def index
  24. @variants = scope.includes(include_list)
  25. .ransack(params[:q]).result
  26. @variants = paginate(@variants)
  27. respond_with(@variants)
  28. end
  29. def new
  30. end
  31. def show
  32. @variant = scope.includes(include_list)
  33. .find(params[:id])
  34. respond_with(@variant)
  35. end
  36. def update
  37. @variant = scope.accessible_by(current_ability, :update).find(params[:id])
  38. if @variant.update(variant_params)
  39. respond_with(@variant, status: 200, default_template: :show)
  40. else
  41. invalid_resource!(@product)
  42. end
  43. end
  44. private
  45. def product
  46. @product ||= Spree::Product.accessible_by(current_ability, :show).friendly.find(params[:product_id]) if params[:product_id]
  47. end
  48. def scope
  49. if @product
  50. variants = @product.variants_including_master
  51. else
  52. variants = Spree::Variant
  53. end
  54. if current_ability.can?(:manage, Variant) && params[:show_deleted]
  55. variants = variants.with_discarded
  56. end
  57. in_stock_only = ActiveRecord::Type::Boolean.new.cast(params[:in_stock_only])
  58. suppliable_only = ActiveRecord::Type::Boolean.new.cast(params[:suppliable_only])
  59. variants = variants.accessible_by(current_ability)
  60. if in_stock_only || cannot?(:view_out_of_stock, Spree::Variant)
  61. variants = variants.in_stock
  62. elsif suppliable_only
  63. variants = variants.suppliable
  64. end
  65. variants
  66. end
  67. def variant_params
  68. params.require(:variant).permit(permitted_variant_attributes)
  69. end
  70. def include_list
  71. [{ option_values: :option_type }, :product, :default_price, :images, { stock_items: :stock_location }]
  72. end
  73. end
  74. end
  75. end