dry-rails icon indicating copy to clipboard operation
dry-rails copied to clipboard

Add support to look up superclass schemas in inherited controllers

Open keymastervn opened this issue 2 years ago • 0 comments

I am having two classes A and B with the following definitions

class A < ApplicationController
  schema(:index) do
    optional(:user_id).value(:string)
  end
  
  def index
    # something
  end
end
class B < A
end
# routes.rb
namespace :api do
  namespace :v1 do
    namespace :public do
      resources :a, only: [:index]
    end

    namespace :enterprise do 
      resources :b, only: [:index]
    end
  end
end

The problem is, B couldn't inherit the schema(:index) defined in the parent controller A, so I have to go with the reuse schema approach. It is even trickier because our ApplicationController has a callback to verify input and exits early

before_action do
  if safe_params && safe_params.failure?
    raise InvalidParams, safe_params.errors(full: true).messages.join(', ')
  end
end

In order to get the dry-schema object from the parent class, this PR checks if the parent class is including the SafeParams module, it then merges the parent schemas to resolve the safe_params for the action.

keymastervn avatar Jun 07 '23 07:06 keymastervn