dry-rb / dry-rails

The official dry-rb railtie
https://dry-rb.org/gems/dry-rails
MIT License
270 stars 27 forks source link

Add support to look up superclass schemas in inherited controllers #61

Open keymastervn opened 1 year ago

keymastervn commented 1 year ago

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.