Skip to content

Commit

Permalink
v5.0.0: Complain about unknown hash values
Browse files Browse the repository at this point in the history
  • Loading branch information
henrik committed Jun 28, 2016
1 parent 504842a commit 1fc9eff
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 1 deletion.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ Also provides conveniences for creating value objects, method objects, query met

`attr_initialize [:bar, :baz!]` defines an initializer that takes one hash argument, assigning `@bar` (optional) and `@baz` (required).

If you pass unknown hash arguments, you will get an `ArgumentError`.

`attr_initialize` can also accept a block which will be invoked after initialization. This is useful for e.g. initializing private data as necessary.


Expand Down
6 changes: 6 additions & 0 deletions lib/attr_extras/attr_initialize.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@ def apply
if name_or_names.is_a?(Array)
hash = value || {}

known_keys = name_or_names.map { |name| name.to_s.sub(/!\z/, "").to_sym }
unknown_keys = hash.keys - known_keys
if unknown_keys.any?
raise ArgumentError, "Got unknown keys: #{unknown_keys.inspect}; allowed keys: #{known_keys.inspect}"
end

name_or_names.each do |name|
set_ivar_from_hash.call(self, name, hash)
end
Expand Down
2 changes: 1 addition & 1 deletion lib/attr_extras/version.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module AttrExtras
VERSION = "4.6.0"
VERSION = "5.0.0"
end
12 changes: 12 additions & 0 deletions spec/attr_extras/attr_initialize_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,18 @@ def self.name
lambda { klass.new(:optional => "X") }.must_raise KeyError
end

it "complains about unknown hash values" do
klass = Class.new do
attr_initialize :foo, [:bar]
end

# Should not raise.
klass.new("Foo", :bar => "Bar")

exception = lambda { klass.new("Foo", :bar => "Bar", :baz => "Baz") }.must_raise ArgumentError
exception.message.must_include "baz"
end

it "accepts a block for initialization" do
klass = Class.new do
attr_initialize :value do
Expand Down

0 comments on commit 1fc9eff

Please sign in to comment.