From e77fb49a39591637998991a4c834746f984abc0a Mon Sep 17 00:00:00 2001 From: Danial Moazen Date: Fri, 10 Nov 2023 11:43:38 -0800 Subject: [PATCH] validate the data before initializing config to fail fast --- lib/attributor/flatpack/config.rb | 14 +++++++++++++- spec/attributor/flatpack/config_spec.rb | 12 ++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/lib/attributor/flatpack/config.rb b/lib/attributor/flatpack/config.rb index 97c229e..06d9728 100644 --- a/lib/attributor/flatpack/config.rb +++ b/lib/attributor/flatpack/config.rb @@ -37,7 +37,19 @@ def self.example(context = nil, **values) example end + def self.validate_data(data) + return true unless data.respond_to?(:keys) + + data.keys.each do |k| + /(.)*/.match?(k) + rescue TypeError => e + raise ArgumentError, 'keys must be symboles or strings' + end + end + def initialize(data = nil) + self.class.validate_data data + @raw = data @contents = {} @@ -171,7 +183,7 @@ def validate_requirements(context) def validate_keys(context) return [] if self.class.options[:allow_extra] - + errors = (@raw.keys.collect(&:to_s) - self.class.keys.keys.collect(&:to_s)).collect do |extra_key| "Unknown key received: #{extra_key.inspect} for #{Attributor.humanize_context(context)}" end diff --git a/spec/attributor/flatpack/config_spec.rb b/spec/attributor/flatpack/config_spec.rb index dddffd9..690841c 100644 --- a/spec/attributor/flatpack/config_spec.rb +++ b/spec/attributor/flatpack/config_spec.rb @@ -240,4 +240,16 @@ it { should_not be_empty } end end + + context 'with data with invalid keys' do + let(:data) do + { + { foo: :baz } => :bar + :foo => :bar + } + end + it 'should fail to initialize' do + expect { subject }.to raise_error(ArgumentError) + end + end end