Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #
- # hash_to_qs.rb - by clinton forbes and ryan allen!
- #
- require 'cgi'
- class Hash
- def self.from_qs(str)
- hash = {}
- str.split('&').collect { |k_v| k_v.split('=') }.each do |pair|
- hash[CGI.unescape(pair[0])] = CGI.unescape(pair[1])
- end
- hash
- end
- def to_qs
- collect do |key, value|
- "#{CGI.escape(key.to_s)}=#{CGI.escape(value.to_s)}"
- end.join('&')
- end
- end
- if __FILE__ == $0
- require 'test/unit'
- class HashToAndFromQSTest < Test::Unit::TestCase
- def setup
- @hash = {'a' => '1', 'b' => '2', 'c' => '3'}
- @qs = 'a=1&b=2&c=3'
- end
- def test_can_convert_hash_to_qs
- assert_equal @qs, @hash.to_qs
- end
- def test_can_convert_qs_to_hash
- assert_equal Hash.from_qs(@qs), @hash
- end
- end
- end
Add Comment
Please, Sign In to add comment