RubyでSTDINやSTDOUTを活用できるCLIツールを書く
CLIツールを作るとき、UNIX哲学が好きな人は、
パイプを活用できるように、STDINから入力を取得したいし、STDOUTへ出力したいですよね。
サンプルとして、STDINから取得した文字列をキャメルケースにしたり、スネークケースにしたりしてSTDOUTに出力するコマンドを作ってみます。
こんなイメージのCLIツールを作ってみます。
$ cat 'hello_world' | mycommand camelize
HelloWorld
$ cat 'HelloWorld' | mycommand snake
hello_world
パイプでつなげるので
$ cat 'hello_world' | mycommand camelize | mycommand snake
hello_world
という無駄なこともできます。
bundler gem で雛形を作成する
まずはbundler gem
コマンドで雛形を作成します。
$ bundler gem mycommand
CLIツールを簡単に作れるgemのThorを利用するので、mycommand.gemspec
ファイルにthor
を追加します。
spec.add_dependency "thor"
とりあえずbundle
を叩いてThorをインストールしておきます。
$ bundle
lib/mycommand.rb
を書きます。コマンドはcamelize
とsnake
を作ります。
require "mycommand/version"
require "thor"
module Mycommand
class CLI < Thor
desc "echo 'hello_world' | mycommand camelize", "Camelize STDIN"
def camelize()
stdin = stdin_read
puts stdin.split('_').map{|s| s.capitalize}.join('')
end
desc "echo 'HelloWorld' | mycommand snake", "Snakecase STDIN"
def snake()
stdin = stdin_read
puts stdin.split(/(?![a-z])(?=[A-Z])/).map{|s| s.downcase}.join('_')
end
private
def stdin_read()
return $stdin.read
end
end
end
bin/mycommand
も書きます。
#!/usr/bin/env ruby
require 'mycommand'
Mycommand::CLI.start
コマンドを試してみる
bin/mycommand
に実行権限を与えます。
$ chmod +x bin/mycommand
コマンド実行を試してみます
$ echo 'hello_world' | bundle exec bin/mycommand camelize
HelloWorld
$ echo 'HelloWorld' | bundle exec bin/mycommand snake
hello_world'
$ echo 'hello_world' | bundle exec bin/mycommand camelize | bundle exec bin/mycommand snake
hello_world'
できました!
あとは、必要に応じてmycommand.gemspec
ファイルのTODOを修正して bundle exec rake install
なりしてしまえばSTDINを入力として受け取れるmycommand
ができます。
というわけで
良いCLIツールライフを!
参考URL
Author And Source
この問題について(RubyでSTDINやSTDOUTを活用できるCLIツールを書く), 我々は、より多くの情報をここで見つけました https://qiita.com/k1LoW/items/9520ad8f45a62c676cb7著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .