1
0
mirror of https://github.com/meineerde/rackstash.git synced 2025-10-17 14:01:01 +00:00

Add helper method to parse URI parameter from an adapter URI

This commit is contained in:
Holger Just 2018-01-23 23:53:31 +01:00
parent c194b00b34
commit 39f12047cb
2 changed files with 50 additions and 1 deletions

View File

@ -5,6 +5,9 @@
# This software may be modified and distributed under the terms
# of the MIT license. See the LICENSE.txt file for details.
require 'cgi'
require 'uri'
require 'rackstash/adapter'
require 'rackstash/encoder/json'
@ -34,6 +37,30 @@ module Rackstash
Rackstash::Adapter.register(self, *matchers)
end
class << self
private
def parse_uri_options(uri)
options = {}
(uri.query || EMPTY_STRING).split(/[&;] */n).each do |option|
next if option.empty?
k, v = option.split('='.freeze, 2).map! { |s| CGI.unescape(s) }
k = k.to_sym
if cur = options[k]
if cur.class == Array
options[k] << v
else
options[k] = [cur, v]
end
else
options[k] = v
end
end
options
end
end
# Create a new adapter instance.
#
# Usually, this method is overwritten by child classes to accept a

View File

@ -12,6 +12,28 @@ require 'rackstash/adapter/base_adapter'
describe Rackstash::Adapter::BaseAdapter do
let(:adapter) { described_class.new }
describe '.parse_uri_options' do
it 'returns a Hash of query options' do
expect(described_class.send :parse_uri_options, URI('/?foo=bar&baz=bums'))
.to eql foo: 'bar', baz: 'bums'
end
it 'does not parse special values' do
expect(described_class.send :parse_uri_options, URI('/?i=42&f=3.14&b=false&a[]=nil'))
.to eql i: '42', f: '3.14', b: 'false', :'a[]' => 'nil'
end
it 'accepts common separators' do
expect(described_class.send :parse_uri_options, URI('/?a=b;c=d&e=f;g=h'))
.to eql a: 'b', c: 'd', e: 'f', g: 'h'
end
it 'parses multiple values of the same key into an array' do
expect(described_class.send :parse_uri_options, URI('/?key=foo&key=bar&key=baz'))
.to eql key: ['foo', 'bar', 'baz']
end
end
describe '#initialize' do
it 'accepts any arguments' do
described_class.new
@ -20,7 +42,7 @@ describe Rackstash::Adapter::BaseAdapter do
end
end
describe '.default_encoder' do
describe '#default_encoder' do
it 'returns an encoder' do
expect(adapter.default_encoder).to respond_to(:encode)
end