元タイトル:JavaScriptのencodeURIComponentはRubyだとどう書く
('14/11/22大幅変更)
String クラスにメソッドを作るモンキーパッチ
JavaScript の encodeURIComponent と encodeURI と同じエンコードするメソッドを String クラスに作りましょう。
class String
def encodeURIComponent
unescaped_form = /([#{Regexp.escape(';/?:@&=+$,<>#%"{}|\\^[]`' + (0x0..0x1f).map{|c| c.chr }.join + "\x7f" + (0x80..0xff).map{|c| c.chr }.join)}])/n
self.force_encoding("ASCII-8BIT").gsub(unescaped_form){ "%%%02X" % $1.ord }
end
def encodeURI
unescaped = /([#{Regexp.escape('<>#%"{}|\\^[]`' + (0x0..0x1f).map{|c| c.chr }.join + "\x7f" + (0x80..0xff).map{|c| c.chr }.join)}])/n
self.force_encoding("ASCII-8BIT").gsub(unescaped){ "%%%02X" % $1.ord }
end
end
文字列を引数を取るメソッド
encodeURIComponent() と encodeURI() と同じく文字列を引数に取るメソッドも作りましょう。
def encodeURIComponent(str)
unescaped_form = /([#{Regexp.escape(';/?:@&=+$,<>#%"{}|\\^[]`' + (0x0..0x1f).map{|c| c.chr }.join + "\x7f" + (0x80..0xff).map{|c| c.chr }.join)}])/n
str.force_encoding("ASCII-8BIT").gsub(unescaped_form){ "%%%02X" % $1.ord }
end
def encodeURI(str)
unescaped = /([#{Regexp.escape('<>#%"{}|\\^[]`' + (0x0..0x1f).map{|c| c.chr }.join + "\x7f" + (0x80..0xff).map{|c| c.chr }.join)}])/n
str.force_encoding("ASCII-8BIT").gsub(unescaped){ "%%%02X" % $1.ord }
end
メソッド名
本当は encode_uri_component
encode_uri
にすべきかも知れませんが由来のわかりやすさ優先で。