简体   繁体   中英

Command Aliasing in Thor

Is it possible to create aliases for commands in Thor?

Much like command aliasing in Commander. https://github.com/tj/commander#command-aliasing

I am able to find aliases for options, but not for the command itself.

Using the example from Thor,

#!/usr/bin/env ruby
require 'thor'

# cli.rb
class MyCLI < Thor
  desc "hello NAME", "say hello to NAME"
  def hello(name)
    puts "Hello #{name}"
  end
end

MyCLI.start(ARGV)

I should be able to run

$ ./cli.rb hello John
Hello John

I would like to alias the command "hello" to "hi" as well.

You can use map for this:

http://www.rubydoc.info/github/wycats/thor/master/Thor#map-class_method

#!/usr/bin/env ruby
require 'thor'

# cli.rb
class MyCLI < Thor

  desc "hello NAME", "say hello to NAME"
  def hello(name)
    puts "Hello #{name}"
  end

  map hi: :hello
end

MyCLI.start(ARGV)

Use method_option for aliases.

#!/usr/bin/env ruby
    require 'thor'

    # cli.rb
    class MyCLI < Thor
      desc "hello NAME", "say hello to NAME"
      method_option :hello , :aliases => "-hello" , :desc => "Hello Command" 
      def hello(name)
        puts "Hello #{name}"
      end
    end

    MyCLI.start(ARGV)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM