LoginSignup
2
0

More than 3 years have passed since last update.

第13回(thor,rubocop)

Last updated at Posted at 2020-12-30

!Mac OS X-10.15.7 !ruby-2.7.1p83

thor

いくつかの振る舞いを一つのコマンドに持たそうとすると,オプションなどを適切に扱う必要が出てくる.そのためにいくつかのCLI builder gemsがあり,ここではthorを学ぶ.

まずは

gem install thor

前作ったhello_rubyに組み込む

require 'thor'
require "hello_rudy/version"

class HelloRudyCLI < Thor
  desc "hello NAME", "say hello to NAME"
  def hello(name)
    puts "Hello " + name
  end
end

HelloRudyCLI.start(ARGV)

これでほぼ動く.CLIという文字列がclass名の最後にないとダメ.

ちゃんと動かすには,さらに修正.

> in hello_rudy.gemspec
  spec.add_runtime_dependency('thor')

> bundle update
> bundle install

> cat lib/hello_rudy/version.rb 
class HelloRudy #
  VERSION = "0.1.0"
end

で出来上がり.

bundleでlocalに動かしてみると

> bundle exec exe/hello_rudy
Commands:
  hello_rudy hello NAME      # say hello to NAME
  hello_rudy help [COMMAND]  # Describe available commands or one specific command

> bundle exec exe/hello_rudy hello Rudy
Hello Rudy

と動く.

rubocop

規約通りにコードが書かれているかをチェックしてくれるもの.

タブとか空白のformatといった簡単なチェック以外に,method lengthとabc sizeというのがある.method lengthはデフォルトは10行以上だと警告.abc sizeというのは,

  • Assignment : 変数への代入
  • Branch : メソッド呼び出し
  • Condition : 条件文

なんかを勘定して基準値を超えると警告.

こんなツールまであるなんてメソッドを短く書くのは本当に重要だとわかる.


  • source ~/grad_members_20f/members/yoshida/c06_thor.org
2
0
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
0