module StrongResources::Controller::Mixin

Attributes

_strong_resources[RW]

Public Class Methods

included(klass) click to toggle source
# File lib/strong_resources/controller/mixin.rb, line 4
def self.included(klass)
  klass.class_eval do
    extend ClassMethods
    class << self
      attr_accessor :_strong_resources
    end
  end

  # In cases when the full jsonapi suite is being used, we
  # can provide much better error feedback when parameters are
  # incorrect.  Without this handler, errors would be generic
  # 500's with unhelpful statuses, but this will give API consumers
  # better feedback about formatting errors with a 400 response.
  if respond_to?(:register_exception)
    register_exception StrongerParameters::InvalidParameter,
      handler: StrongResources::ExceptionHandler
  end
end

Public Instance Methods

apply_strong_param(relationship_payload, permitted) click to toggle source

TODO: refactor

# File lib/strong_resources/controller/mixin.rb, line 44
def apply_strong_param(relationship_payload, permitted)
  if relationship_payload[:meta][:method] == :disassociate
    raise 'not allowed disass' unless permitted[:_disassociate]
  end

  if relationship_payload[:meta][:method] == :destroy
    raise 'not allowed destroy' unless permitted[:_destroy]
  end

  unless relationship_payload[:attributes].respond_to?(:permit)
    relationship_payload[:attributes] = ActionController::Parameters.new(relationship_payload[:attributes])
  end

  relationship_payload[:attributes] = relationship_payload[:attributes].permit(permitted)
  relationship_payload[:relationships].each_pair do |name, rp|
    [rp].flatten.each do |_rp|
      apply_strong_param(_rp, permitted[:relationships][name])
    end
  end
end
apply_strong_params() click to toggle source

TODO: refactor

# File lib/strong_resources/controller/mixin.rb, line 24
def apply_strong_params
  deserializer = deserialized_params

  unless deserializer.attributes.respond_to?(:permit)
    deserializer.attributes = ActionController::Parameters.new(deserializer.attributes)
  end
  deserializer.attributes = deserializer.attributes.permit(strong_resource)

  deserializer.relationships.each_pair do |name, relationship_payload|
    if strong_resource[:relationships].has_key?(name)
      [relationship_payload].flatten.each do |rp|
        apply_strong_param(rp, strong_resource[:relationships][name])
      end
    else
      deserializer.relationships.delete(name)
    end
  end
end
strong_resource() click to toggle source
# File lib/strong_resources/controller/mixin.rb, line 65
def strong_resource
  resources = self.class._strong_resources
  raise RuntimeError, "You need to define the `strong_resource` for #{self.class.name}" if resources.nil?
  resource = resources[action_name.to_sym]
  raise RuntimeError, "Missing `strong_resource` parameters for #{self.class.name}##{action_name}" if resource.nil?
  _params = params
  resource.permits(self)
end