Skip to content

Commit

Permalink
Pass keyword arguments to each rule
Browse files Browse the repository at this point in the history
This also fixes uncached calls to `block.parameters` after calling `with`
  • Loading branch information
flash-gordon committed Jun 28, 2019
1 parent b30cd42 commit 29d4aff
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 8 deletions.
19 changes: 11 additions & 8 deletions lib/dry/validation/function.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,21 +19,24 @@ class Function
# @api private
option :block

# @!attribute [r] block_options
# @return [Hash]
# @api private
option :block_options, default: -> { block ? map_keywords(block) : EMPTY_HASH }

private

# Extract options for the block kwargs
#
# @return [Hash]
# @param [Proc] block Callable
# @return Hash
#
# @api private
def block_options
return EMPTY_HASH unless block

@block_options ||= block
def map_keywords(block)
block
.parameters
.select { |arg| arg[0].equal?(:keyreq) }
.map(&:last)
.map { |name| [name, BLOCK_OPTIONS_MAPPINGS[name]] }
.select { |arg,| arg.equal?(:keyreq) }
.map { |_, name| [name, BLOCK_OPTIONS_MAPPINGS[name]] }
.to_h
end
end
Expand Down
2 changes: 2 additions & 0 deletions lib/dry/validation/rule.rb
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,8 @@ def each(*macros, &block)
end
end

@block_options = map_keywords(block) if block

self
end

Expand Down
9 changes: 9 additions & 0 deletions spec/integration/contract/class_interface/rule/each_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@ def self.name
rule(hash: :another_nums).each do
key.failure('invalid') if value < 3
end

rule(:nums).each do |context:|
context[:sum] ||= 0
context[:sum] += value
end
end
end

Expand All @@ -38,6 +43,10 @@ def self.name
expect(contract.(nums: [4], hash: { another_nums: ['oops', 1, 4] }).errors.to_h)
.to eql(hash: { another_nums: { 0 => ['must be an integer'], 1 => ['invalid'] } })
end

it 'passes block options' do
expect(contract.(nums: [10, 20]).context[:sum]).to eql(30)
end
end

context 'using a simple macro' do
Expand Down

0 comments on commit 29d4aff

Please sign in to comment.