Skip to content

Commit c4d0520

Browse files
committed
decode and decode_hex have a new option downcase to decide if input string should be downcased. For backwards compatability this is true, but in future will change to not changing case of inputs.
1 parent 0667599 commit c4d0520

File tree

2 files changed

+27
-5
lines changed

2 files changed

+27
-5
lines changed

lib/encoded_id/reversible_id.rb

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -35,17 +35,17 @@ def encode_hex(hexs)
3535
end
3636

3737
# Decode the hash to original array
38-
def decode(str)
38+
def decode(str, downcase: true)
3939
raise InvalidInputError if max_length_exceeded?(str)
4040

41-
encoded_id_generator.decode(convert_to_hash(str))
41+
encoded_id_generator.decode(convert_to_hash(str, downcase))
4242
rescue ::Hashids::InputError => e
4343
raise EncodedIdFormatError, e.message
4444
end
4545

4646
# Decode hex strings from a hash
47-
def decode_hex(str)
48-
integers = encoded_id_generator.decode(convert_to_hash(str))
47+
def decode_hex(str, downcase: true)
48+
integers = encoded_id_generator.decode(convert_to_hash(str, downcase))
4949
hex_represention_encoder.integers_as_hex(integers)
5050
end
5151

@@ -114,8 +114,9 @@ def humanize_length(hash)
114114
hash.gsub(split_regex, "\\0#{split_with}")
115115
end
116116

117-
def convert_to_hash(str)
117+
def convert_to_hash(str, downcase)
118118
clean = str.gsub(split_with, "")
119+
clean = clean.downcase if downcase
119120
map_equivalent_characters(clean)
120121
end
121122

test/encoded_id/test_reversible_id.rb

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,27 @@ def test_it_decodes_back_to_an_integer_id
111111
assert_equal [123], id
112112
end
113113

114+
def test_it_decodes_back_to_an_integer_id_with_case_insensitivity
115+
coded = "P5w9-z27j"
116+
id = ::EncodedId::ReversibleId.new(salt: salt).decode(coded, downcase: true)
117+
assert_equal [123], id
118+
end
119+
120+
def test_it_correctly_decodes_encodedids_with_case_sensitivity
121+
coded1 = "e5bd-ea58"
122+
coded2 = "e5bd-eA58"
123+
a = ::EncodedId::Alphabet.new(["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "a", "b", "c", "d", "e"])
124+
enc = ::EncodedId::ReversibleId.new(salt: salt, alphabet: a)
125+
id1 = enc.decode(coded1, downcase: false)
126+
assert_equal [123], id1
127+
id2 = enc.decode(coded2)
128+
assert_equal [123], id2
129+
id2 = enc.decode(coded2, downcase: true)
130+
assert_equal [123], id2
131+
id2 = enc.decode(coded2, downcase: false)
132+
assert_equal [], id2
133+
end
134+
114135
def test_it_decodes_back_to_id_with_mapped_chars
115136
coded = "p5w9-z27i" # 'i' used instead of 'j'
116137
id = ::EncodedId::ReversibleId.new(salt: salt).decode(coded)

0 commit comments

Comments
 (0)