Skip to content

Commit

Permalink
Merge pull request #54 from Drakula2k/fix-letters-only-alphabet
Browse files Browse the repository at this point in the history
Fix fallback in case of letters-only alphabet
  • Loading branch information
jcypret authored Jul 29, 2018
2 parents ea3a1cc + c57e6c1 commit 08716b9
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/hashid/rails.rb
Original file line number Diff line number Diff line change
Expand Up @@ -101,14 +101,16 @@ def hashid_encode(id)
end

def hashid_decode(id, fallback:)
decoded_hashid = hashids.decode(id.to_s)
fallback_value = fallback ? id : nil
decoded_hashid = hashids.decode(id.to_s)

if Hashid::Rails.configuration.sign_hashids
valid_hashid?(decoded_hashid) ? decoded_hashid.last : fallback_value
else
decoded_hashid.first || fallback_value
end
rescue Hashids::InputError
fallback_value
end

def valid_hashid?(decoded_hashid)
Expand Down
16 changes: 16 additions & 0 deletions spec/hashid/rails_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,22 @@
expect(decoded_id).to eq(100_117)
end
end

context "with letters-only alphabet" do
before do
Hashid::Rails.configure { |config| config.alphabet = [*"A".."Z"].join }
end

it "returns nil when already decoded id" do
decoded_id = FakeModel.decode_id(100_117, fallback: false)
expect(decoded_id).to eq(nil)
end

it "returns already decoded id when fallback" do
decoded_id = FakeModel.decode_id(100_117, fallback: true)
expect(decoded_id).to eq(100_117)
end
end
end

shared_examples_for "finders" do
Expand Down

0 comments on commit 08716b9

Please sign in to comment.