From b9d8c71cecdca157bbc98c0eb7900d4084ced0f7 Mon Sep 17 00:00:00 2001 From: Manuel Familia Date: Tue, 16 Feb 2016 19:58:30 -0500 Subject: [PATCH] Allow configuration of alphabet for hashids --- README.md | 3 +++ lib/hashid/rails.rb | 10 ++++++++-- spec/hashid/rails_spec.rb | 29 +++++++++++++++++++++++++++++ 3 files changed, 40 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 872111d..f9b078a 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,9 @@ easily reverse engineer your ids, create an initializer and: Hashid::Rails.configure do |config| config.secret = 'my secret' config.length = 6 + # config.alphabet is optional, hashids provides a default + # alphabet that consists of all characters [a-zA-Z0-9] + config.alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' end ``` diff --git a/lib/hashid/rails.rb b/lib/hashid/rails.rb index 4a478c6..b438b75 100644 --- a/lib/hashid/rails.rb +++ b/lib/hashid/rails.rb @@ -38,7 +38,12 @@ module ClassMethods def hashids secret = Hashid::Rails.configuration.secret length = Hashid::Rails.configuration.length - Hashids.new("#{table_name}#{secret}", length) + alphabet = Hashid::Rails.configuration.alphabet + + arguments = ["#{table_name}#{secret}", length] + arguments << alphabet if alphabet.present? + + Hashids.new(*arguments) end def encode_id(id) @@ -61,11 +66,12 @@ def model_reload? end class Configuration - attr_accessor :secret, :length + attr_accessor :secret, :length, :alphabet def initialize @secret = '' @length = 6 + @alphabet = nil end end diff --git a/spec/hashid/rails_spec.rb b/spec/hashid/rails_spec.rb index ecee359..c82c089 100644 --- a/spec/hashid/rails_spec.rb +++ b/spec/hashid/rails_spec.rb @@ -56,6 +56,35 @@ end end + describe 'alphabet' do + let(:expected_alphabet) { 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' } + let(:config) { Hashid::Rails.configuration } + + context 'with custom alphabet' do + before :each do + Hashid::Rails.configure do |config| + config.alphabet = expected_alphabet + end + end + + it 'initializes hashid correctly' do + expect(Hashids).to receive(:new) + .with('models', config.length, expected_alphabet) + + Model.hashids + end + end + + context 'with no custom alphabet' do + it 'initializes hashid correctly' do + expect(Hashids).to receive(:new) + .with('models', config.length) + + Model.hashids + end + end + end + end describe '#reload' do