Sha256: ceff0c20442bc7d3429c55ec0730c0288e4f1d10b3d093844560bda12dfa716e

Contents?: true

Size: 1.03 KB

Versions: 1

Compression:

Stored size: 1.03 KB

Contents

module Encore
  module Helpers
    module ControllerHelper
      HTTP_ERROR_STATUS_CODE = 422
      HTTP_SUCCESS_CODE = 200
      HTTP_SUCCESS_CREATED_CODE = 201

      # Inject itself into the ActionController::Base class
      def self.inject_into_action_controller
        ::ActionController::Base.send :include, self
      end

      # Save the entity and return a JSON response
      def process!(entity)
        error_status = HTTP_ERROR_STATUS_CODE
        success_status = success_status_code_from_entity(entity)

        if entity.save
          render json: entity, status: success_status
        else
          render json: { errors: entity.errors }, status: error_status
        end
      end

    protected

      # Return the status code to send after a successful processing
      # of an entity, depending on its context
      def success_status_code_from_entity(entity)
        case entity.context
          when :create then HTTP_SUCCESS_CREATED_CODE
          else              HTTP_SUCCESS_CODE
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
encore-0.0.3 lib/encore/helpers/controller_helper.rb