0
0
Fork 0

added custom parameter

This commit is contained in:
Gibheer 2012-11-29 19:44:12 +01:00
parent 2762f68363
commit 8c7eed073c
3 changed files with 103 additions and 0 deletions

View File

@ -28,6 +28,9 @@ module Zero
attr_reader :payload
alias_method(:post, :payload)
# get all custom parameters
attr_reader :custom
# creates a new parameter instance
#
# This should never be called directly, as it will be generated for you.
@ -37,6 +40,32 @@ module Zero
def initialize(environment)
@query = extract_query_params(environment)
@payload = extract_payload_params(environment)
@custom = {}
environment['zero.params.custom'] = @custom
end
# get a parameter
#
# With this method you can get the value of a parameter. First the
# custom parameters are checked, then payload and after that the query
# ones.
#
# *Beware, that this may lead to security holes!*
#
# @param key [String] a key to look for
# @returns [String] the value of the key
def [](key)
@custom[key] || @payload[key] || @query[key]
end
# set a custom key/value pair
#
# Use this method if you want to set a custom parameter for later use. If
# the key was already set it will be overwritten.
# @param key [String] the key to use for saving the parameter
# @param value [Object] the value for the key
def []=(key, value)
@custom[key] = value
end
private

View File

@ -0,0 +1,56 @@
require 'spec_helper'
describe Zero::Request::Parameter, '#[]' do
subject { Zero::Request::Parameter.new(env) }
context 'without parameters' do
let(:env) { EnvGenerator.get('/foo') }
it 'returns the custom parameter' do
subject['foo'] = 'bar'
expect(subject['foo']).to eq('bar')
end
end
context 'with query parameters' do
let(:env) { EnvGenerator.get('/foo?foo=bar') }
it 'returns the query parameter' do
expect(subject['foo']).to eq('bar')
end
it 'returns the custom parameter' do
subject['foo'] = 'baz'
expect(subject['foo']).to eq('baz')
end
end
context 'with payload parameters' do
let(:env) do
EnvGenerator.post('/foo', {
:input => 'foo=bar', 'CONTENT_TYPE' => 'multipart/form-data'
})
end
it 'returns the payload value' do
expect(subject['foo']).to eq('bar')
end
it 'returns the custom parameter' do
subject['foo'] = 'baz'
expect(subject['foo']).to eq('baz')
end
end
context 'with query and payload parameters' do
let(:env) do
EnvGenerator.post('/foo?foo=baz', {
:input => 'foo=bar', 'CONTENT_TYPE' => 'multipart/form-data'
})
end
it 'returns the payload parameter' do
expect(subject['foo']).to eq('bar')
end
end
end

View File

@ -0,0 +1,18 @@
require 'spec_helper'
describe Zero::Request::Parameter, '#custom' do
subject { Zero::Request::Parameter.new(env) }
let(:env) { EnvGenerator.get('/foo') }
it 'returns a set custom parameter' do
subject['foo'] = 'bar'
expect(subject.custom['foo']).to eq('bar')
end
it 'returns the latest set value' do
subject['foo'] = 'first'
subject['foo'] = 'latest'
expect(subject.custom['foo']).to eq('latest')
end
end