Search code examples
rubythor

Adding a --version option to a Ruby Thor CLI


How do I add a --version option to my Ruby Thor command line interface application.

For example I want to be able to run

$ thor_app --version
> thor_app version 1.0.0

This question is related to Run a CLI Thor app without arguments or task name, but specifically to add a --version option which does not require a task.

Note
This was written following the self-answer format. Addition answers and updates are encouraged


Solution

  • I had some luck with this approach:

    class CLI < Thor
      map %w[--version -v] => :__print_version
    
      desc "--version, -v", "print the version"
      def __print_version
        puts FooBar::VERSION
      end
    end
    

    The leading underscores ensures there isn't a command like yourapp version, and forces yourapp --version or yourapp -v. The desc content will allow it to show up as -v, --version without exposing __print_version.