表é¡ã®éããªãã§ãã
ä¸è¨ã®ãã¼ã¸ã®ãParse CLI options into a Hashãã®é
ç®ãè¦ãã¨ã以ä¸ã®ããã« parse
ã¡ã½ããã« :into
ã§ããã·ã¥ãªãã¸ã§ã¯ãã渡ãã¨èªåã§ãããã³ã°ãã¦ãããã¨ããå°å³ã«ä¾¿å©ãªæ©è½ã追å ãããã
ä¸è¨ã®URLããæç²
require 'optparse' require 'optparse/date' require 'optparse/uri' cli = OptionParser.new do |options| options.define '--from=DATE', Date options.define '--url=ENDPOINT', URI options.define '--names=LIST', Array end config = {} args = %w[ --from 2016-02-03 --url https://blog.blockscore.com/ --names John,Daniel,Delmer ] cli.parse(args, into: config) config.keys # => [:from, :url, :names] config[:from] # => #<Date: 2016-02-03 ((2457422j,0s,0n),+0s,2299161j)> config[:url] # => #<URI::HTTPS https://blog.blockscore.com/> config[:names] # => ["John", "Daniel", "Delmer"]
:into
ã§ä¾¿å©ã«ãªãã®ã¯ããããã®ã®ããã®ãµã³ãã«ãè¦ã㨠define
ã£ã¦ä½ã ãããã¨ãçããªãã·ã§ã³åï¼-u
ã¨ãï¼ãæå®ããå ´åã©ããªãã®ï¼ã£ã¦ã¨ãããè²ã
ã¨çåã ã£ãã®ã§èª¿ã¹ã¦ã¿ãã
define is ä½
æ
å¼±ãªã®ã§ãªãã¡ã¬ã³ã¹ããã¥ã¢ã«ã«è¼ã£ã¦ãªãAPIã ãã define
ã使ã£ããªãã·ã§ã³ã®å®ç¾©ãããã¨ããªãã£ãï¼å®ã¯è¼ã£ã¦ããã®ãã¨æã£ã¦ãããããããã©ãã£ã±ãè¼ã£ã¦ãªãï¼ã
ã¨ããããã§Rubyã®ã½ã¼ã¹ã確èªãã¦è¦ãã¨ãããªæã
https://github.com/ruby/ruby/blob/v2_4_2/lib/optparse.rb#L1465-L1505
æç²ããã¨ä»¥ä¸ã®ããã«ããã¤ã使ã£ã¦ãã on
ã¡ã½ãããå
é¨ã§å¼ã³åºãã¦ããã¡ã½ãããªãã§ããã
def define(*opts, &block) top.append(*(sw = make_switch(opts, block))) sw[0] end def on(*opts, &block) define(*opts, &block) self end
ã½ã¼ã¹å
ã®é°å²æ°ããããã¨ã on
ã¯å
¬éç¨ã§ define
ã¯å
é¨ã§ä½¿ãç¨ã£ã½ãæ°ããããã©*1ãæ®éã«å¼ã³åºãããã©ã£ã¡ã§ãè¯ãã®ãããããªããã¾ããä»ã¾ã§éã on
ç³»ã使ãã°è¯ãããªã£ã¦æ°ããã¾ããâ¦â¦ã
ãªãã·ã§ã³å is ä½
å²ãå½ã¦ããªãã·ã§ã³åã£ã¦ã©ã決ã¾ãã®ãã
options.on '-a, '--argument=VAL'
ã¿ããã«å®ç¾©ããæã«ã©ã£ã¡ã使ãããã®ããªã¨ãã話ã§ãããã¾ããããªãã·ã§ã³åã« -
ãå«ã¾ãã¦ããå ´åã©ããªãã®ãï¼ãã¿ãã¬ããã¨:"foo-bar"
ã¿ããã«ãªãï¼ãªã©çåã湧ãã¾ãããã
ãããç¥ãã«ã¯ãã£ãã :into
ãªãã·ã§ã³ã®æµãã追ãå¿
è¦ãããã®ã§ãããçµè«ãå
ã«æ¸ãã¦ããã¨
- çããªãã·ã§ã³åã¨é·ããªãã·ã§ã³åããã£ãå ´åé·ããªãã·ã§ã³åã使ç¨ããã
- ãªãã·ã§ã³åã®å
é ãã¤ãã³ãåãé¤ããæååã
.to_sym
ããå¤ã«ãªã
ã¨ããåä½ã®ããã§ãã
ããã°ã©ã çã«ã¯
- ããã§
:into
ããã£ãå ´åã®åä½ãå®ç¾©ããã¦ãã¦ããªãã·ã§ã³åã.to_sym
ãã¦ãã - ããã·ã¥ã®ååã¨ãã¦ã¯
switch_name
ã®å¤ã使ãã㦠switch_name
ã¯é·ãååãåªå ãã¦ä½¿ç¨ãã
ã¨ããæµãã®ããã§ããã
ã¾ã¨ã
OptionParser.new do |options| options.on '-r', '--ruby=VAL' do |val| val.downcase end options.on '-p', '--perl=VAL' do |val| val.upcase end options.on '-g', '--go-lang' do 'go' end options.on '-d' do true end options.on_tail '-h', '--help', 'hi' end
ãããªå®ç¾©ãããå ´åã into
ãªãã·ã§ã³ã§Hashã渡ããå ´åã¯
{ ruby: 'ruby', perl: 'PERL', 'go-lang': 'go', d: true }
ãããªå¤ãå¾ããã¾ãã便å©ã§ããã
ãµã³ãã«ã½ã¼ã¹ã³ã¼ãã¨ãã¹ãã±ã¼ã¹ã¯ä»¥ä¸ã«ããã¾ãï¼ä¸»ã« test/unit
ã使ã£ã¦ã¿ããã£ãã ãwï¼ã
https://github.com/sugamasao/optparser_ruby24_into_sample
*1:å®éã®ã¨ããã¯ã©ããªãã§ããããï¼