Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Macros do not support validation on root object #688

Open
midnight-wonderer opened this issue Aug 12, 2021 · 1 comment
Open

Macros do not support validation on root object #688

midnight-wonderer opened this issue Aug 12, 2021 · 1 comment

Comments

@midnight-wonderer
Copy link

Describe the bug

I extracted a macro into a reusable module, like this:

module ReusableRule
  extend ::ActiveSupport::Concern

  included do
    register_macro(:reusable_macro) do
      # do some validations here 
    end
  end
end

and use it like this:

class SomeContracr < ::Dry::Validation::Contract
  params do
    # define some params here
  end

  include ::ReusableRule
  rule(path_to: :inner_hash).validate(:reusable_macro)
end

which works fine.

But I cannot use it on the root hash, like this:

class SomeContracr < ::Dry::Validation::Contract
  params do
    # define some params here
  end

  include ::ReusableRule
  rule.validate(:reusable_macro)
end

Expected behavior

The macro should validate the root hash the same way as when I use it on an inner hash.

Actual behavior

dry-validation throws an ArgumentError

lib/dry/validation/values.rb:59:in `[]': +key+ must be a valid path specification (ArgumentError)

My environment

  • Ruby version: 3.0
  • OS: Docker image (Debian)

Suggestion

Probably adding

return data if args.size < 1

around here.

@midnight-wonderer
Copy link
Author

Oops! my bad
I can avoid the error myself by detecting keys.empty? in my macro.

resolved_value, base_path = if keys.empty?
  [values.data, []]
else
  [value, path.keys]
end
# use resolved_value and base_path for validations

If I call value as I described initially, the error will be triggered.

I'll leave this thread open and let the maintainer decide whether the inconsistencies are something to be handled by dry-rb, or by consumers. I would understand if there is no good solution for the library, though.
Feel free to close the thread if that is the case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant