Skip to content

Commit

Permalink
Raise an ArgumentError if unsupported options are passed
Browse files Browse the repository at this point in the history
  • Loading branch information
mak-dunkelziffer committed Sep 6, 2023
1 parent 857998a commit 06962b7
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 2 deletions.
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ This project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html

### Compatible changes

-
- Calling `assignable_values_for` with unsupported options will raise an error.



Expand Down
21 changes: 20 additions & 1 deletion lib/assignable_values/active_record/restriction/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,24 @@ class Base

attr_reader :model, :property, :options, :values, :default, :secondary_default

SUPPORTED_OPTIONS = [
:allow_blank,
:decorate,
:default,
:include_old_value,
:message,
:multiple,
:secondary_default,
:through,
].freeze
private_constant :SUPPORTED_OPTIONS

def initialize(model, property, options, &values)
@model = model
@property = property
@options = options
@values = values
validate_supported_options!
ensure_values_given
setup_default
define_assignable_values_method
Expand Down Expand Up @@ -274,8 +287,14 @@ def ensure_values_given
@values or @options[:through] or raise NoValuesGiven, 'You must supply the list of assignable values by either a block or :through option'
end

def validate_supported_options!
unsupported_options = @options.keys - SUPPORTED_OPTIONS
if unsupported_options.any?
raise UnsupportedOption,
"The following options are not supported: #{unsupported_options.map { |o| ":#{o}" }.join(', ')}"
end
end
end
end
end
end

1 change: 1 addition & 0 deletions lib/assignable_values/errors.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ class Error < StandardError; end
class DelegateUnavailable < Error; end
class NoValuesGiven < Error; end
class NoDefault < Error; end
class UnsupportedOption < Error; end
end
8 changes: 8 additions & 0 deletions spec/assignable_values/active_record_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,14 @@ def save_without_validation(record)
end.to raise_error(AssignableValues::NoValuesGiven)
end

it 'should raise an error when called with unsupported options' do
expect do
Song.disposable_copy do
assignable_values_for :genre, unsupported_option: 42
end
end.to raise_error(AssignableValues::UnsupportedOption, 'The following options are not supported: :unsupported_option')
end

context 'when validating virtual attributes' do

before :each do
Expand Down

0 comments on commit 06962b7

Please sign in to comment.