LoginSignup
3
2

More than 5 years have passed since last update.

RubyでJSのURIエンコードを

Last updated at Posted at 2014-11-09

元タイトル: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 にすべきかも知れませんが由来のわかりやすさ優先で。

参考

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2