Skip to content

Commit

Permalink
Merge pull request #10 from mfamilia/master
Browse files Browse the repository at this point in the history
Allow configuration of alphabet for hashids
  • Loading branch information
jcypret committed Mar 11, 2016
2 parents 6ea90a1 + b9d8c71 commit 409639d
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 2 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
```

Expand Down
10 changes: 8 additions & 2 deletions lib/hashid/rails.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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

Expand Down
29 changes: 29 additions & 0 deletions spec/hashid/rails_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 409639d

Please sign in to comment.