ちょっとハマった上に無駄骨だった
環境変数http_proxyをURI.parseした時の要素が気になって、調べるコードを書いてみた。
最初はこんな感じのコード
require 'uri';{}.tap{|h| URI.parse(ENV['http_proxy']||ENV['HTTP_PROXY']||'').tap{|uri| uri.instance_variables.each{|var| h[var]||=uri.instance_variable_get(var)}}}
もっとシンプルな方法があるはずとリファレンスをみる。
URI::Generic#select(*components)とURI::Generic.componentを見つける!
早速、使ってみた。
require 'uri' uri = URI.parse( ENV['http_proxy'] || ENV['HTTP_PROXY'] || '' ) components = URI::Generic.component uri.select(*components) # => ArgumentError: expected of components of URI::HTTP (scheme, userinfo, host, port, path, query, fragment)
ダメじゃん。なして?
要素を確認。
URI::Generic.component # => [:scheme, :userinfo, :host, :port, :registry, :path, :opaque, :query, :fragment]
なぬ?
URI::Generic.componentで取得できる要素とURI::Generic#selectが受け付ける
要素が違うじゃん。
余分な要素を抜いてみた。
require 'uri' uri = URI.parse( ENV['http_proxy'] || ENV['HTTP_PROXY'] || '' ) components = URI::Generic.component - [:registry, :opaque] uri.select(*components) # => ["http", "user:password", "proxy.hoge.co.jp", 8080, "", nil, nil]
これでいいのか〜
んじゃ、最初のを書き直して・・・(上下は同じ結果)
require 'uri';{}.tap{|h| (URI::Generic.component-[:registry,:opaque]).tap{|c| h.merge!(Hash[*c.zip(URI.parse(ENV['http_proxy']||ENV['HTTP_PROXY']||'').select(*c)).flatten])}} require 'uri';{}.tap{|h| (URI::Generic.component-[:registry,:opaque]).tap{|c| c.zip(URI.parse(ENV['http_proxy']||ENV['HTTP_PROXY']||'').select(*c)).each{|k,v| h[k]||=v}}}
最初のより長くなってるし、要素の意味も全くわかっていない(>_<)
要素の意味は後で調べよう。