Permalink
Browse files

allow action params to read arrays

  • Loading branch information...
TiteiKo committed Aug 26, 2016
1 parent fde8975 commit 579aa059a732736011eda3914ff702f458c7a30a
Showing with 25 additions and 4 deletions.
  1. +6 −2 lib/hanami/action/base_params.rb
  2. +11 −2 test/action/params_test.rb
  3. +8 −0 test/fixtures.rb
@@ -93,11 +93,11 @@ def get(key)
key, *keys = key.to_s.split(GET_SEPARATOR)
return if key.nil?

result = self[key.to_sym]
result = self[_key_for_get(key)]

Array(keys).each do |k|
break if result.nil?
result = result[k.to_sym]
result = result[_key_for_get(k)]
end

result
@@ -146,6 +146,10 @@ def _extract_params
def _router_params(fallback = {})
env.fetch(ROUTER_PARAMS, fallback)
end

def _key_for_get(key)
key =~ /\A\d+\z/ ? key.to_i : key.to_sym
end
end
end
end
@@ -232,7 +232,11 @@
describe '#get' do
describe 'with data' do
before do
@params = TestParams.new(name: 'John', address: { line_one: '10 High Street', deep: { deep_attr: 1 } })
@params = TestParams.new(
name: 'John',
address: { line_one: '10 High Street', deep: { deep_attr: 1 } },
array: [{ name: 'Lenon' }, { name: 'Wayne' }]
)
end

it 'returns nil for nil argument' do
@@ -254,6 +258,11 @@
it 'returns nil for uknown nested param' do
@params.get('address.unknown').must_be_nil
end

it 'allows to read datas under arrays' do
@params.get('array.0.name').must_equal 'Lenon'
@params.get('array.1.name').must_equal 'Wayne'
end
end

describe 'without data' do
@@ -438,7 +447,7 @@
actual[:address].must_be_kind_of(::Hash)
actual[:address][:deep].must_be_kind_of(::Hash)
end

it 'does not stringify values' do
input = { 'name' => 123 }
params = TestParams.new(input)
@@ -782,6 +782,14 @@ class TestParams < Hanami::Action::Params
required(:deep_attr).filled(:str?)
end
end

optional(:array).maybe do
each do
schema do
required(:name).filled(:str?)
end
end
end
end
end

0 comments on commit 579aa05

Please sign in to comment.