dry-initializer icon indicating copy to clipboard operation
dry-initializer copied to clipboard

Add attribute readers for unknown attributes

Open jonspalmer opened this issue 2 years ago • 4 comments

default behavior remains unchanged

Unknown params and options are ignored but stored in their own attr_reader

class Test::Foo
 extend Dry::Initializer

 param :foo
 param :bar, optional: true
end

foo = Test::Foo.new(1, 2, 3, 4)
foo.__dry_initializer_unknown_params__ # => [3, 4]
class Test::Foo
 extend Dry::Initializer

 option :foo
 options :bar, optional: true
end

foo = Test::Foo.new(foo: 1, bar: 2, fizz: 3, buzz: 4)
foo.__dry_initializer_unknown_options__ # => {fizz: 3, buzz: 4}

rest params and rest options names are configurable

class Test::Foo
 extend Dry::Initializer

 param :foo
 param :bar, optional: true
 rest_param :unknown_params
end

foo = Test::Foo.new(1, 2, 3, 4)
foo.unknown_params # => [3, 4]
class Test::Foo
 extend Dry::Initializer

 option :foo
 options :bar, optional: true
 rest_options :unknown_options
end

foo = Test::Foo.new(foo: 1, bar: 2, fizz: 3, buzz: 4)
foo.unknown_options # => {fizz: 3, buzz: 4}

rest params and rest options can be turned off for strict mode

This adds support for strict checking of params and options: #68

class Test::Foo
 extend Dry::Initializer

 param :foo
 param :bar, optional: true
 rest_param false
end

Test::Foo.new(1, 2, 3, 4) => raises ArgumentError
class Test::Foo
 extend Dry::Initializer

 option :foo
 options :bar, optional: true
 rest_options :unknown_options
end

Test::Foo.new(foo: 1, bar: 2, fizz: 3, buzz: 4) # raises ArgumentError

jonspalmer avatar Jul 17 '21 21:07 jonspalmer

Rubocop linting is needed but I'm loath to do that first as the class/module nesting changes lead to every line of the files getting whitespace changes that would obscure the code really being touched.

jonspalmer avatar Jul 17 '21 21:07 jonspalmer

cc @nepalez perhaps for a reivew?

jonspalmer avatar Jul 24 '21 11:07 jonspalmer

Hi there 😊 Was this idea abandoned? It would be a really great addition!

simonc avatar Aug 17 '22 12:08 simonc

I'd also like to see this idea revived. Is there any way I can help?

hangsu avatar Nov 20 '22 17:11 hangsu