Guest User

Untitled

a guest
Apr 19th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.83 KB | None | 0 0
  1. #
  2. # hash_to_qs.rb - by clinton forbes and ryan allen!
  3. #
  4. require 'cgi'
  5.  
  6. class Hash
  7.  
  8. def self.from_qs(str)
  9. hash = {}
  10. str.split('&').collect { |k_v| k_v.split('=') }.each do |pair|
  11. hash[CGI.unescape(pair[0])] = CGI.unescape(pair[1])
  12. end
  13. hash
  14. end
  15.  
  16. def to_qs
  17. collect do |key, value|
  18. "#{CGI.escape(key.to_s)}=#{CGI.escape(value.to_s)}"
  19. end.join('&')
  20. end
  21.  
  22. end
  23.  
  24. if __FILE__ == $0
  25.  
  26. require 'test/unit'
  27.  
  28. class HashToAndFromQSTest < Test::Unit::TestCase
  29.  
  30. def setup
  31. @hash = {'a' => '1', 'b' => '2', 'c' => '3'}
  32. @qs = 'a=1&b=2&c=3'
  33. end
  34.  
  35. def test_can_convert_hash_to_qs
  36. assert_equal @qs, @hash.to_qs
  37. end
  38.  
  39. def test_can_convert_qs_to_hash
  40. assert_equal Hash.from_qs(@qs), @hash
  41. end
  42.  
  43. end
  44.  
  45. end
Add Comment
Please, Sign In to add comment