µ-optparseを使って.rvmrcを生成
optparseのラッパーであるµ-optparseを使って.rvmrcを生成するスクリプトを書いてみた。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'rubygems' | |
require 'micro-optparse' | |
options = Parser.new { |p| | |
p.banner = "Generate .rvmrc file." | |
p.version = "0.1" | |
p.option :ruby, "Version of Ruby interpreter installed with RVM", :default => RUBY_VERSION | |
p.option :gemset, "Name of RVM gemset", :default => File.basename(`pwd`.strip) | |
p.option :force, "Write file whether it exists or not", :default => false | |
}.process! | |
file = ".rvmrc" | |
if File.exist? file and !options[:force] | |
abort "#{file} already exists!" | |
else | |
line = "rvm use #{options[:ruby]}@#{options[:gemset]}" | |
File.open(file, "w") { |f| f.write(line) } | |
puts %(Write "#{line}" to #{file}.) | |
end |
オプションは下記の通り。–helpでも見れるし、コードを読むだけでもわかりやすい。
- -r, –ruby
- Rubyのバージョン。デフォルトはこのスクリプトを実行しているRuby
- -g, –gemset
- gemset名。デフォルトはカレントディレクトリ名
- -f, –force
- 指定された場合、.rvmrcが存在しようがしまいが書きだす
たとえば次のコマンドでは"rvm use 1.9.2@rails31"を.rvmrcに書きだす。
$ rvmrc -r 1.9.2 -g rails31 -f
µ-optparseは宣言していない引数が指定された場合や、引数の値が条件(正規表現、特定の値、もしくは任意の判定条件を)にマッチしない場合にエラー文を出してくれたりと結構便利。–helpや–versionにも勝手に対応してくれるので、ちょこっとしたスクリプトを書くのに向いている。
まぁこんなコマンドを叩くぐらいなら直接echoした場合のほうが手軽だろうけど、どちらかというとオプション指定ナシで現在の環境の.rvmrcを吐くのが目的なので、実際問題オプションは必要なかったりする…かも