Skip to content

Commit 51155a7

Browse files
authored
feat: add hook hints (#135)
Signed-off-by: Manuel Schönlaub <[email protected]>
1 parent 50bdf48 commit 51155a7

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# frozen_string_literal: true
2+
3+
module OpenFeature
4+
module SDK
5+
module Hooks
6+
class Hints < DelegateClass(Hash)
7+
ALLOWED_TYPES = [String, Symbol, Numeric, TrueClass, FalseClass, Time, Hash, Array].freeze
8+
9+
def initialize(hash = {})
10+
hash.each do |key, value|
11+
assert_allowed_key(key)
12+
assert_allowed_value(value)
13+
end
14+
@hash = hash.dup
15+
super(@hash)
16+
freeze
17+
end
18+
19+
private
20+
21+
def assert_allowed_key(key)
22+
raise ArgumentError, "Only String or Symbol are allowed as keys." unless key.is_a?(String) || key.is_a?(Symbol)
23+
end
24+
25+
def assert_allowed_value(value)
26+
allowed_type = ALLOWED_TYPES.any? { |t| value.is_a?(t) }
27+
raise ArgumentError, "Only #{ALLOWED_TYPES.join(", ")} are allowed as values." unless allowed_type
28+
end
29+
end
30+
end
31+
end
32+
end
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# frozen_string_literal: true
2+
3+
require "spec_helper"
4+
5+
require "open_feature/sdk/hooks/hints"
6+
7+
RSpec.describe OpenFeature::SDK::Hooks::Hints do
8+
let(:hint_hash) { {key: [], nested: {key: []}} }
9+
subject(:hints) { described_class.new(hint_hash) }
10+
context "Immutability" do
11+
it "is frozen" do
12+
expect(hints).to be_frozen
13+
end
14+
15+
it "does not allow addition of new keys" do
16+
expect { hints[:new_key] = "new_value" }.to raise_error(FrozenError)
17+
end
18+
19+
it "does allow modification of existing values" do
20+
expect(hints[:key]).to_not be_frozen
21+
expect { hints[:key] << "abc" }.to_not raise_error
22+
end
23+
24+
it "does not allow deletion of keys" do
25+
expect { hints.delete(:key) }.to raise_error(FrozenError)
26+
end
27+
28+
it "allows reading of keys" do
29+
expect(hints[:key]).to eq([])
30+
end
31+
32+
it "only allows string keys" do
33+
expect { described_class.new(1 => []) }.to raise_error(ArgumentError) do |e|
34+
expect(e.message).to include("Only String or Symbol are allowed as keys")
35+
end
36+
end
37+
38+
it "only allows values of certain types" do
39+
expect { described_class.new(key: Object.new) }.to raise_error(ArgumentError) do |e|
40+
expect(e.message).to include("Only String, Symbol, Numeric, TrueClass, FalseClass, Time, Hash, Array are allowed as values")
41+
end
42+
end
43+
44+
it "does not freeze the original hash" do
45+
expect(hint_hash).not_to be_frozen
46+
end
47+
end
48+
end

0 commit comments

Comments
 (0)