Module: LZString::EncodedURI
- Included in:
- LZString
- Defined in:
- lib/lzstring/encoded_uri.rb
Overview
Module for URI encoding/decoding
Constant Summary collapse
- KEY_STR_URI_SAFE =
Key string for URI encoding
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$".freeze
Class Method Summary collapse
-
.compress_to_encoded_uri_component(input) ⇒ String
Compress a string to URI encoding.
-
.decompress_from_encoded_uri_component(input) ⇒ String?
Decompress a string from URI encoding.
Class Method Details
.compress_to_encoded_uri_component(input) ⇒ String
Compress a string to URI encoding
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# File 'lib/lzstring/encoded_uri.rb', line 10 def self.compress_to_encoded_uri_component(input) return "" if input.nil? || input.empty? begin # Force input to UTF-8 encoding input = input.to_s.dup.force_encoding(Encoding::UTF_8) # Use the _compress function with URI parameters LZString._compress(input, 6) do |a| KEY_STR_URI_SAFE[a % KEY_STR_URI_SAFE.length] end rescue # Log error and return empty string on failure # STDERR.puts "URI compression error: #{e.message}" "" end end |
.decompress_from_encoded_uri_component(input) ⇒ String?
Decompress a string from URI encoding
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
# File 'lib/lzstring/encoded_uri.rb', line 31 def self.decompress_from_encoded_uri_component(input) return "" if input.nil? || input.empty? begin # Ensure input is properly encoded input = input.to_s.dup.force_encoding(Encoding::UTF_8) # Replace spaces with plus signs input = input.gsub(" ", "+") # Initialize reverse dictionary reverse_dict = {} KEY_STR_URI_SAFE.each_char.with_index { |c, i| reverse_dict[c] = i } # Use the _decompress function with URI parameters result = LZString._decompress(input.length, 32) do |index| if index >= input.length 0 else # Get character value from dictionary or return 0 reverse_dict[input[index]] || 0 end end # Ensure proper UTF-8 encoding of the result if result.is_a?(String) # Force UTF-8 encoding and replace invalid bytes result.force_encoding(Encoding::UTF_8) # Check if the result is valid UTF-8, if not try to repair unless result.valid_encoding? # Replace invalid sequences with a replacement character result = result.encode(Encoding::UTF_8, Encoding::UTF_8, invalid: :replace, undef: :replace, replace: "?") end end result rescue # Log error and return nil on failure # STDERR.puts "URI decompression error: #{e.message}" nil end end |