rails / thor

Thor is a toolkit for building powerful command-line interfaces.
http://whatisthor.com/
MIT License
5.13k stars 552 forks source link

Allow for nested no_commands blocks. #697

Closed tmfnll closed 4 years ago

tmfnll commented 4 years ago

Allow for nested no_commands blocks. 🌈

Background

In certain circumstances we may wish to nest no_commands blocks.

However, since when exiting the no_commands block the @no_commands instance var is reset to false, we get unexpected behaviour.

For example, this will show warnings stating that the method foo is missing usage and a description:

class Foo < Thor

  no_method do
    attr_reader :bar

    def foo
      'foo!'
    end
  end
end

This particular example is trivially solved but things get more difficult when, say, including modules.

# lib/thor/base.rb
def no_commands
  @no_commands = true
  yield
ensure
   @no_commands = false
end

Solution

This change uses a NestedContext object to track the depth of the no_command blocks and ensure that we only start creating commands again once we've left all of them.

Comments

rafaelfranca commented 4 years ago

Thank you for the pull request. I think this solution is too complex just to allow nested no_commands. Can you explain why you need nested no_commands?

tmfnll commented 4 years ago

Hello, I have been working on refactoring some scripts for a Rails application and wanted to make use of the ActiveModel validation API. So I included the ActiveModel::Validations module which created the nested no_commands via an attr_reader.