RubyでURIを処理したいときは標準ライブラリのURIを使うことが多いですが、Addressable gemを使うことでより完結にわかりやすくコードを書くことが出来ることもあります。今回はそんなAddressable gemの使い方を学んでいきましょう。
インストール
Addressableはgemなのでインストールが必要です。コマンドラインからaddressableをインストールしましょう。
$ gem install addressable
Adressable::URIの使い方
使用前にはrequireが必要です。そこに注意しましょう。
例えば以下のようにURIをparseすることが出来ます。
require 'addressable/uri'
uri = Addressable::URI.parse("https://www.example.com/path/to/end.html?test=1&test2=2")
uri.scheme # => "https"
uri.host # => "www.example.com"
uri.path # => "/path/to/end.html"
# 拡張子があれば拡張子だけ抜き出すことが出来る
uri.extname # => ".html"
uri.query_values # => {"test"=>"1", "test2"=>"2"}
個人的に嬉しいポイントとしてはqueryをHash形式で操作することが出来るところです。
例えばURIのqueryを追加・削除したいとき
query_valuesに代入も出来るのでここにHashを追加・削除してあげることであらたにqueryを追加・削除することが出来ます。簡単。幸せ。
require 'addressable/uri'
uri = Addressable::URI.parse("https://www.example.com/path/to/end.html?test=1&test2=2")
# queryを追加する
queries = uri.query_values
queries["test3"] = 3
uri.query_values = queries
uri.to_s # => "https://www.example.com/path/to/end.html?test=1&test2=2&test3=3"
# queryを削除する
queries.delete("test2")
uri.query_values = queries
uri.to_s # => "https://www.example.com/path/to/end.html?test=1&test3=3"
例えばURIのqueryを全削除したいとき
Hashをnilにしてあげればqueryを全削除することが出来ます。幸せ。
require 'addressable/uri'
uri = Addressable::URI.parse("https://www.example.com/path/to/end.html?test=1&test2=2")
# query_valuesにnilを追加するとqueryを全削除する
uri.query_values = nil
uri.to_s # => "https://www.example.com/path/to/end.html"
まとめ
Rubyの強みはコミュニティの強さ・gemの豊富さだと思います。なので使えるものは使って速く実装出来るときは使えばよいかと思います。
またこれらの機能を自分ならどう実装するかを考えてみるのもプログラミング能力向上によいトレーニングかと思いますのでぜひ考えてみてください。