LoginSignup
12
14

More than 5 years have passed since last update.

Rubyでサブコマンド付きのコマンドを簡単に書けるThor (2) -hオプションを有効にする

Posted at

問題

サブコマンドのヘルプを見るにはdemo help subcommandと入力する必要があります。
出来れば demo subcommand -hと打ちたい所です。

# ok
$ demo help abc
print 'abc'

# error
$ demo abc -h
demo abc requires at least 0 argument:

解法

class_optionの設定とThor::invoke_taskの上書きで実現します。

demo.rb
#! /usr/bin/env ruby
# -*- coding: utf-8 -*-

require 'rubygems'
require 'thor'

class Demo < Thor
  class_option :help, :type => :boolean, :aliases => '-h', :desc => 'Help message.'

  desc "abc", "print 'abc'"
  def abc
    puts 'abcdefg!'
  end

  desc "efg [option]", "print 'efg'"
  option :upcase, :type => :boolean, :aliases => '-u', :desc => "disp upcase"
  def efg
    if options[:upcase]
      puts 'EFG!'
    else
      puts 'efg!'
    end
  end

  no_tasks do
    # デフォルトメソッドを上書きして -h を処理
    # defined in /lib/thor/invocation.rb
    def invoke_task(task, *args)
      if options[:help]
        Demo.task_help(shell, task.name)
      else
        super
      end
    end
  end
end

Demo.start

demo subcommand -hdemo help subcommandのどちらでも可能になります。

$ chmod +x demo2
$ demo2 abc -h
print 'abc'
$ demo2 help abc
print 'abc'

実例

Milkodeの次のバージョンに組み込まれます。milkコマンドの内部で利用しました。

tomykairaさんのパッチにより実現されました。

12
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
14