LoginSignup
0

More than 1 year has passed since last update.

チャート式ruby-appendix-VI(thor, rubocop)

Last updated at Posted at 2020-11-10

!Mac OS X-10.15.7 !ruby-2.7.1p83

thor

いくつかの振る舞いを一つのコマンドに持たそうとすると,オプションなどを適切に扱う必要が出てきます.そのためにいくつかのCLI builder gemsがあります.人気は,http://52.198.30.45/categories/CLI+Builderで調べることができます.ここではthorを紹介します.これはRakefileに似たDSLで実現できます.

まずは

gem install thor

してください.

前に作ったhello_rudyにcliのinterfaceを組み込んでみましょう.

 1  #+begin_src ruby
 2  require 'thor'
 3  require "hello_rudy/version"
 4  
 5  class HelloRudyCLI < Thor
 6    desc "hello NAME", "say hello to NAME"
 7    def hello(name)
 8      puts "Hello " + name
 9    end
10  end
11  
12  HelloRudyCLI.start(ARGV)
13  #+end_src

と修正するとほぼ動きます.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

とCLIらしく動いてくれます.

さらにrake installすればいろんなとこから使えます.Thorはruby on railsなんかでも使われています.gitもだったかな...https://github.com/erikhuda/thor/wikiに詳しい解説があります.my_help, qiita_orgはthorを使っています.

rubocop

前の週のchart式でちょっと紹介したrubocopっというのがあります.これはcode formatterとかlinterと呼ばれる類のツールです.規約通りにコードが書かれているかをチェックしてくれます.

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

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

なんかを勘定して基準値を超えると警告します.これらの要素が多いと,codeが複雑になるので,避けなさいという警告です.長いcodeを書くようになったら,これらのツールを定期的に使ってcodeを整理するようにしましょう.methodは短いほどわかりやすいんです.

github issue

rubocopにauto correctがあります.

gem install rubocop
rubocop --auto-correct fibonacci.rb

とかで直してくれます.

もうだいぶ前になるんですが,これで悲惨な目に遭いました.その様子は,

にあります.

これはOSS(Open Source Software)開発ではありがちなことです.でもね,このフットワークの軽さがいいところなんです.すぐにメンターが出てきて,開発者が対応してくれる.逆に皆さんもすぐにOSSにcontribute(貢献)することができます.

OSSの定義は,ライセンスがOSSならOK.open source initiative 定義で調べてみてください.my_help やqiita_orgもOSSです.日本語でいいんで,issueやpull requestを投げましょう.


  • source ~/git_hub/ruby_docs/chart_style_ruby/c06_thor.org

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
What you can do with signing up
0