Commit 4e80792b authored by Pedro Pombeiro's avatar Pedro Pombeiro

Add lookup methods in `Variables::Collection`

Allows for quick lookup when expanding variable values.
parent f962e3ad
......@@ -10,13 +10,18 @@ module Gitlab
def initialize(variables = [], errors = nil)
@variables = []
@var_hash = {}
@errors = errors
variables.each { |variable| self.append(variable) }
end
def append(resource)
tap { @variables.append(Collection::Item.fabricate(resource)) }
tap do
item = Collection::Item.fabricate(resource)
@variables.append(item)
@var_hash[item[:key]] = item
end
end
def concat(resources)
......@@ -36,10 +41,26 @@ module Gitlab
end
end
def [](key)
@var_hash[key]
end
def size
@variables.size
end
def to_runner_variables
self.map(&:to_runner_variable)
end
def include?(obj)
return false unless obj.is_a?(Hash) && obj.has_key?(:key)
key = obj.fetch(:key)
found_var = @var_hash[key]
!found_var.nil? && found_var.to_runner_variable == Collection::Item.fabricate(obj).to_runner_variable
end
def to_hash
self.to_runner_variables
.map { |env| [env.fetch(:key), env.fetch(:value)] }
......
......@@ -98,6 +98,60 @@ RSpec.describe Gitlab::Ci::Variables::Collection do
end
end
describe '#[]' do
variable = { key: 'VAR', value: 'value', public: true, masked: false }
collection = described_class.new([variable])
it 'returns nil for a non-existent variable name' do
expect(collection['UNKNOWN_VAR']).to be_nil
end
it 'returns Item for an existent variable name' do
expect(collection['VAR']).to be_an_instance_of(Gitlab::Ci::Variables::Collection::Item)
expect(collection['VAR'].to_runner_variable).to eq(variable)
end
end
describe '#size' do
it 'returns zero for empty collection' do
collection = described_class.new([])
expect(collection.size).to eq(0)
end
it 'returns 2 for collection with 2 variables' do
collection = described_class.new(
[
{ key: 'VAR1', value: 'value', public: true, masked: false },
{ key: 'VAR2', value: 'value', public: true, masked: false }
])
expect(collection.size).to eq(2)
end
end
describe '#include?' do
it 'returns false for unknown variable' do
collection = described_class.new([])
expect(collection.include?({ key: 'VAR', value: 'value', public: true, masked: false })).to eq(false)
end
it 'returns false for unsupported scenario of variable name argument' do
collection = described_class.new([{ key: 'VAR', value: 'value', public: true, masked: false }])
expect(collection.include?('VAR')).to eq(false)
end
it 'returns true for known variable' do
variable = { key: 'VAR', value: 'value', public: true, masked: false }
collection = described_class.new([variable])
expect(collection.include?(variable)).to eq(true)
end
end
describe '#to_runner_variables' do
it 'creates an array of hashes in a runner-compatible format' do
collection = described_class.new([{ key: 'TEST', value: '1' }])
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment