LoginSignup
2
3

More than 5 years have passed since last update.

単機能のRuby製自作コマンドのGemをつくって配布する

Last updated at Posted at 2016-12-03

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のコード

2
3
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
2
3