Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

validate the data before initializing config to fail fast #11

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion lib/attributor/flatpack/config.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {}

Expand Down Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions spec/attributor/flatpack/config_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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