From 3e6104c25586e4b423792cb2e2a994a7b4e6af2e Mon Sep 17 00:00:00 2001 From: Lisa Ugray Date: Mon, 7 Jan 2019 09:50:44 -0500 Subject: [PATCH] ostruct.rb: refine arity failure message * lib/ostruct.rb (method_missing): raise exceptions with proper arity messages --- lib/ostruct.rb | 4 +++- spec/ruby/library/openstruct/method_missing_spec.rb | 5 +++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/lib/ostruct.rb b/lib/ostruct.rb index a758a65979..c3b0546d5f 100644 --- a/lib/ostruct.rb +++ b/lib/ostruct.rb @@ -213,7 +213,7 @@ def method_missing(mid, *args) # :nodoc: len = args.length if mname = mid[/.*(?==\z)/m] if len != 1 - raise ArgumentError, "wrong number of arguments (#{len} for 1)", caller(1) + raise ArgumentError, "wrong number of arguments (given #{len}, expected 1)", caller(1) end modifiable?[new_ostruct_member!(mname)] = args[0] elsif len == 0 # and /\A[a-z_]\w*\z/ =~ mid # @@ -221,6 +221,8 @@ def method_missing(mid, *args) # :nodoc: new_ostruct_member!(mid) unless frozen? @table[mid] end + elsif @table.key?(mid) + raise ArgumentError, "wrong number of arguments (given #{len}, expected 0)" else begin super diff --git a/spec/ruby/library/openstruct/method_missing_spec.rb b/spec/ruby/library/openstruct/method_missing_spec.rb index eefe30661a..e8dcd1cca0 100644 --- a/spec/ruby/library/openstruct/method_missing_spec.rb +++ b/spec/ruby/library/openstruct/method_missing_spec.rb @@ -36,6 +36,11 @@ os = OpenStruct.new lambda { os.method_missing(:test, 1, 2, 3) }.should raise_error(NoMethodError) end + + it "raises an ArgumentError when the key exists" do + os = OpenStruct.new(test: 20) + lambda { os.method_missing(:test, 1, 2, 3) }.should raise_error(ArgumentError) + end end describe "OpenStruct#method_missing when not passed any additional arguments" do -- 2.20.1