Skip to content

Commit 40defbf

Browse files
committed
Validate arguments for method_option and class_option
`method_option` and `class_option` require a String or Symbol as the first argument. This can be somewhat confusing when `method_options` and `class_options` require a Hash as argument.
1 parent 5fb6206 commit 40defbf

File tree

3 files changed

+23
-1
lines changed

3 files changed

+23
-1
lines changed

lib/thor.rb

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,7 @@ def method_options(options = nil)
141141
# # magic
142142
# end
143143
#
144-
# method_option :foo => :bar, :for => :previous_command
144+
# method_option :foo, :for => :previous_command
145145
#
146146
# def next_command
147147
# # magic
@@ -161,6 +161,9 @@ def method_options(options = nil)
161161
# :hide - If you want to hide this option from the help.
162162
#
163163
def method_option(name, options = {})
164+
unless [ Symbol, String ].any? { |klass| name.is_a?(klass) }
165+
raise ArgumentError, "Expected a Symbol or String, got #{name.inspect}"
166+
end
164167
scope = if options[:for]
165168
find_and_refresh_command(options[:for]).options
166169
else

lib/thor/base.rb

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -326,6 +326,9 @@ def class_options(options = nil)
326326
# :hide:: -- If you want to hide this option from the help.
327327
#
328328
def class_option(name, options = {})
329+
unless [ Symbol, String ].any? { |klass| name.is_a?(klass) }
330+
raise ArgumentError, "Expected a Symbol or String, got #{name.inspect}"
331+
end
329332
build_option(name, options, class_options)
330333
end
331334

spec/thor_spec.rb

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -750,6 +750,22 @@ def hi(name)
750750
expect(klass.start(%w(hi --loud jose))).to eq("Hi JOSE")
751751
end
752752

753+
it "method_option raises an ArgumentError if name is not a Symbol or String" do
754+
expect do
755+
Class.new(Thor) do
756+
method_option loud: true, type: :boolean
757+
end
758+
end.to raise_error(ArgumentError, "Expected a Symbol or String, got {:loud=>true, :type=>:boolean}")
759+
end
760+
761+
it "class_option raises an ArgumentError if name is not a Symbol or String" do
762+
expect do
763+
Class.new(Thor) do
764+
class_option loud: true, type: :boolean
765+
end
766+
end.to raise_error(ArgumentError, "Expected a Symbol or String, got {:loud=>true, :type=>:boolean}")
767+
end
768+
753769
it "passes through unknown options" do
754770
klass = Class.new(Thor) do
755771
desc "unknown", "passing unknown options"

0 commit comments

Comments
 (0)