hello_command
という名前のgemをつくります。
コマンドも同名のhello_command
です。
単機能コマンドつくるだけだったらThorとかめんどくさいので使いません。
雛形を生成する
bundle gem hello_command -b
で雛形を生成してくれます。
名前が既存のgemと被ってるとめんどくさそうなのであらかじめ同名のgemが無いことをrubygems.orgなどで確認しておきます。
$ bundle gem hello_command -b
Creating gem 'hello_command'...
MIT License enabled in config
create hello_command/Gemfile
create hello_command/.gitignore
create hello_command/lib/hello_command.rb
create hello_command/lib/hello_command/version.rb
create hello_command/hello_command.gemspec
create hello_command/Rakefile
create hello_command/README.md
create hello_command/bin/console
create hello_command/bin/setup
create hello_command/.travis.yml
create hello_command/test/test_helper.rb
create hello_command/test/hello_command_test.rb
create hello_command/LICENSE.txt
create hello_command/exe/hello_command
Initializing git repo in /Users/miminashi/projects/hello_command
.gemspecを編集する
hello_command.gemspec
をvimなどで開きます。
spec.summary
, spec.description
, spec.homepage
あたりは必須です。
ここを書き換えておかないとあとでgemをビルドするときにおこられます。
依存するgemはGemfileには書かずに、spec.add_development_dependency
の次の行あたりに、
spec.add_dependency "haikunator"
といった感じで追加します。
自作コマンドのコードを書く
exe/hello_command
をvimなどで開きます。
好きなようにrubyのコードを書きます。
今回はrequireひとつとputsがひとつあるだけです。
# !/usr/bin/env ruby
require "hello_command"
require "haikunator"
puts "#{Haikunator.haikunate(0, ' ')}, #{Haikunator.haikunate(0, ' ')}"
書いたコードを実行してみる
bundle exec exe/hello_command
で実行できます。
望む動作になるまで書いてはこれを実行します。
$ bundle exec exe/hello_command
hidden river, young wave
gemをビルドする
bundle exec rake build
でビルドできます。
$ bundle exec rake build
hello_command 0.1.0 built to pkg/hello_command-0.1.0.gem.
pkg/hello_command-0.1.0.gem
が出来上がったパッケージです。
rubygems.orgなどにアップロードしなくても、とりあえずこのファイルを配布すれば自作したコマンドを誰でもインストール可能になります。
gemをインストールする
gem install {gemファイルのパス}
でインストールできます。
$ gem install pkg/hello_command-0.1.0.gem
Successfully installed hello_command-0.1.0
Parsing documentation for hello_command-0.1.0
Installing ri documentation for hello_command-0.1.0
Done installing documentation for hello_command after 0 seconds
1 gem installed
あとはいくらでも遊べます。
$ hello_command
withered violet, withered violet
$ hello_command
green fire, lively smoke
$ hello_command
作成したgemのコード