Skip to content

Commit

Permalink
Validate arguments for method_option and class_option
Browse files Browse the repository at this point in the history
`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.
  • Loading branch information
p8 committed Aug 9, 2023
1 parent 5fb6206 commit 40defbf
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 1 deletion.
5 changes: 4 additions & 1 deletion lib/thor.rb
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ def method_options(options = nil)
# # magic
# end
#
# method_option :foo => :bar, :for => :previous_command
# method_option :foo, :for => :previous_command
#
# def next_command
# # magic
Expand All @@ -161,6 +161,9 @@ def method_options(options = nil)
# :hide - If you want to hide this option from the help.
#
def method_option(name, options = {})
unless [ Symbol, String ].any? { |klass| name.is_a?(klass) }
raise ArgumentError, "Expected a Symbol or String, got #{name.inspect}"
end
scope = if options[:for]
find_and_refresh_command(options[:for]).options
else
Expand Down
3 changes: 3 additions & 0 deletions lib/thor/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,9 @@ def class_options(options = nil)
# :hide:: -- If you want to hide this option from the help.
#
def class_option(name, options = {})
unless [ Symbol, String ].any? { |klass| name.is_a?(klass) }
raise ArgumentError, "Expected a Symbol or String, got #{name.inspect}"
end
build_option(name, options, class_options)
end

Expand Down
16 changes: 16 additions & 0 deletions spec/thor_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -750,6 +750,22 @@ def hi(name)
expect(klass.start(%w(hi --loud jose))).to eq("Hi JOSE")
end

it "method_option raises an ArgumentError if name is not a Symbol or String" do
expect do
Class.new(Thor) do
method_option loud: true, type: :boolean
end
end.to raise_error(ArgumentError, "Expected a Symbol or String, got {:loud=>true, :type=>:boolean}")
end

it "class_option raises an ArgumentError if name is not a Symbol or String" do
expect do
Class.new(Thor) do
class_option loud: true, type: :boolean
end
end.to raise_error(ArgumentError, "Expected a Symbol or String, got {:loud=>true, :type=>:boolean}")
end

it "passes through unknown options" do
klass = Class.new(Thor) do
desc "unknown", "passing unknown options"
Expand Down

0 comments on commit 40defbf

Please sign in to comment.