Rubyでコマンドを作る環境を整えてみる

はじめに

普段の仕事でほぼ毎日Rubyを書いているがもっぱらRailsばかりなのでもっと気軽にスクリプトを書いていこうと思い。Rubyで書いたプログラムをコマンドとして呼び出せる環境を考えてみた。

やった事

RubyCLIツールを作りたいという事でThorを追加

gem i thor

コマンドとして実行したいので実行ファイルにはshebangをつけて拡張子なしで/binに、本体は/lib以下に分けて置くディレクトリ構成にする

~/scripts/lib/thor_sample/thor_sample.rb
~/scripts/bin/thor_sample

最低限やりたい事を試すためにサンプルのスクリプトを作成

thor_sample.rb

require "thor"

module ThorSample
    class CLI < Thor
        desc "command", "print 'thor sample'"
        def command
            puts "thor sample"
        end
        desc "command2", "print 'hulk sample'"
        def command2
            puts "hulk sample"
        end
    end
end

bin/thor_sample

#!/usr/bin/env ruby
require 'thor'
require_relative '../lib/thor_sample/thor_sample'
ThorSample::CLI.start(ARGV)

pathを通して実行権限を付与

echo 'export PATH="$HOME/scripts/bin:$PATH"' >> ~/.zprofile
source ~/.zprofile
chmod 755 ~/scripts/bin/thor_sample
$thor_sample command
thor sample
$thor_sample command2
hulk sample

気軽にスクリプトを呼び出すのが目的なのに毎回必ず引数を渡さないといけないは面倒なのでデフォルトのコマンドを設定する。
最初はbinファイルの中でARGVが空ならデフォルトコマンドを入れた配列を渡そうと思ったがThorでdefault_taskが設定出来たので素直にこれを使用する。

class CLI < Thor
    default_task :command
    ~
end
$thor_sample
thor sample

これでRubyで書いたプログラムをコマンドとして実行出来るようになった。あとは自分で作りたいと思ったプログラムを追加していくだけ。

仕事でフレームワークを使っていると書いているプログラムの範囲が限定される。
それはそれで良いのだがたまに自分の頭で思いついたアィディアでなにかが実現出来た時は嬉しいので、これでプログラムを楽しんで書く事が捗ればよいと思う。