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

Fix values reader with hash paths #549

Merged
merged 2 commits into from
Jun 14, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 7 additions & 9 deletions lib/dry/validation/values.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# frozen_string_literal: true

require 'dry/equalizer'
require 'dry/schema/path'
require 'dry/validation/constants'

module Dry
Expand Down Expand Up @@ -40,16 +41,13 @@ def initialize(data)
#
# @api public
def [](*args)
if args.size.equal?(1)
case (key = args[0])
when Symbol then data[key]
when String then self[*key.split(DOT).map(&:to_sym)]
when Array then self[*key]
else
raise ArgumentError, '+key+ must be a symbol, string, array, or a list of keys for dig'
end
return data.dig(*args) if args.size > 1

case (key = args[0])
when Symbol, String, Array, Hash
data.dig(*Schema::Path[key].to_a)
else
data.dig(*args)
raise ArgumentError, '+key+ must be a valid path specification'
end
end

Expand Down
8 changes: 6 additions & 2 deletions spec/unit/values_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,18 @@
expect(values[:address, :city]).to eql('Paris')
end

it 'works with a hash' do
expect(values[address: :city]).to eql('Paris')
end

it 'works with an array' do
expect(values[%i[address city]]).to eql('Paris')
end

it 'raises on unpexpected argument type' do
expect { values[{}] }
expect { values[123] }
.to raise_error(
ArgumentError, '+key+ must be a symbol, string, array, or a list of keys for dig'
ArgumentError, '+key+ must be a valid path specification'
)
end
end
Expand Down