Skip to content

Commit

Permalink
Support receiving dry-validation contracts directly
Browse files Browse the repository at this point in the history
  • Loading branch information
timriley committed Sep 2, 2024
1 parent 951f8cc commit 919ff62
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 15 deletions.
16 changes: 13 additions & 3 deletions lib/hanami/action/validatable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -187,12 +187,22 @@ def params(klass = nil, &block)
# @api public
# @since 2.2.0
def contract(klass = nil, &block)
# TODO: Next steps...
# 1. assign the contract class to the action
# 2. in .new, initialize the contract from its class and assign to an ivar
# (this should mean we can support contracts with their own deps)
# 3. in #call, inject the contract instance into the params, which can then call it
if klass.nil?
klass = const_set(PARAMS_CLASS_NAME, Class.new(Params))
klass.contract(&block)
params_class = const_set(PARAMS_CLASS_NAME, Class.new(Params))
params_class.contract(&block)
elsif klass < Dry::Validation::Contract
params_class = const_set(PARAMS_CLASS_NAME, Class.new(Params))
params_class.instance_variable_set(:@_validator, klass.new)
else
params_class = klass
end

@params_class = klass
@params_class = params_class
end
end
end
Expand Down
20 changes: 9 additions & 11 deletions spec/support/fixtures.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1930,23 +1930,21 @@ def handle(request, response)
end
end

class ExternalContractParams < Hanami::Action::Params
contract do
params do
required(:birth_date).filled(:date)
required(:book).schema do
required(:title).filled(:str?)
end
class ExternalContract < Dry::Validation::Contract
params do
required(:birth_date).filled(:date)
required(:book).schema do
required(:title).filled(:str?)
end
end

rule(:birth_date) do
key.failure("you must be 18 years or older") if value < Date.today << (12 * 18)
end
rule(:birth_date) do
key.failure("you must be 18 years or older") if value < Date.today << (12 * 18)
end
end

class ExternalContractAction < ContractAction
contract ExternalContractParams
contract ExternalContract
end

class WhitelistedUploadDslContractAction < Hanami::Action
Expand Down
2 changes: 1 addition & 1 deletion spec/unit/hanami/action/contract_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
end
end

describe "provided by a standlone params class using a contract" do
describe "provided by a standlone contract class" do
let(:action) { ExternalContractAction.new }

context "when it has errors" do
Expand Down

0 comments on commit 919ff62

Please sign in to comment.