ruby で uri ライブラリを使った処理を書いてみたので、ここにメモします。
コード
google スプレッドシートの URI を入力として、キー情報を取得する処理を考えてみました。
require 'uri' def sheet_key(string) def invalid_msg(str, expected_str, actual_str) "#{str} is invalid: expected a (#{expected_str}) but got: (#{actual_str})" end google_spreadsheet_scheme = 'https' google_spreadsheet_host = 'docs.google.com' google_spreadsheet_path = "^/spreadsheets\/\\w\/\\w+/edit$" uri = URI.parse(string) if uri.scheme != google_spreadsheet_scheme then raise invalid_msg("scheme", google_spreadsheet_scheme, uri.scheme) elsif uri.host != google_spreadsheet_host then raise invalid_msg("host", google_spreadsheet_host, uri.host) elsif !uri.path.match(google_spreadsheet_path) raise invalid_msg('path', google_spreadsheet_path, uri.path) end return uri.path.split('/')[-2] end
uri ライブラリの使い方
uri とは
uriとはUniform Resource Identifierの略で、インターネット上のサーバーやサービス、データなどにアクセスするために用いられるurlを拡張した識別子です。
uri ライブラリを使うには
uri ライブラリは、Ruby の標準パッケージに含まれているので、追加インストールは必要ないです。
利用するには require メソッドで取り込む必要があります。Ruby のプログラムで uri ライブラリを利用するには、次の例のように記述します。
require 'uri'
URI オブジェクト
URI オブジェクトの使用例は以下の通りです。
(google スプレッドシートの uri を想定)
parse メソッドで引数に指定された uri を規則に沿って解析し、記載された情報を格納したオブジェクトを返してくれます。
require 'uri' uri = URI.parse("https://docs.google.com/spreadsheets/d/*****/edit#gid=*****")
解析結果
irb(main):002:0> uri = URI.parse("https://docs.google.com/spreadsheets/d/*****/edit#gid=*****") irb(main):005:0> p uri.scheme "https" => "https" irb(main):006:0> p uri.host "docs.google.com" => "docs.google.com" irb(main):007:0> p uri.port 443 => 443 irb(main):008:0> p uri.path "/spreadsheets/d/*****/edit" => "/spreadsheets/d/*****/edit"
regex
def valid_url?(url) url_regexp = /^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/ix url =~ url_regexp ? true : false end
オプション:
i-大文字と小文字を区別しません
x-正規表現の空白を無視