Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make minimum hash length configurable. #7

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.rdoc
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@ In your model, add a single line.
end

== Customization
If you want your hash ids to be different than some other website using the same plugin, you can throw a random string (salt) at hash_id to make it hash out unique ids for your app.
If you want your hash ids to be different than some other website using the same plugin, you can throw a random string (salt) at hash_id to make it hash out unique ids for your app. You can also customize the minimum hash length.

class Post < ActiveRecord::Base
hash_id salt: 'bring_your_own_salt'
hash_id salt: 'bring_your_own_salt', min_length: 3
end

== Limitations
Expand Down
15 changes: 8 additions & 7 deletions lib/hashids_rails.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,18 @@ def hash_id(options = {})
require 'hashids'
extend ClassMethods
include InstanceMethods
cattr_accessor :hash_salt
cattr_accessor :hash_salt, :min_hash_length
self.hash_salt = (options[:salt] || default_salt)
self.min_hash_length = (options[:min_length] || 3)
end

def self.hide(id, salt)
hashids = Hashids.new(salt, 3)
def self.hide(id, salt, min_hash_length)
hashids = Hashids.new(salt, min_hash_length)
hashids.encode id
end

def self.show(id, salt)
hashids = Hashids.new(salt, 3)
def self.show(id, salt, min_hash_length)
hashids = Hashids.new(salt, min_hash_length)
decoded = hashids.decode id
decoded[0] if decoded
end
Expand All @@ -39,7 +40,7 @@ def has_hashed_id?
end

def dehash_id(hashed_id)
HashidsRails.show(hashed_id, self.hash_salt)
HashidsRails.show(hashed_id, self.hash_salt, self.min_hash_length)
end

# Generate a default salt from the Model name
Expand All @@ -52,7 +53,7 @@ def default_salt

module InstanceMethods
def to_param
HashidsRails.hide(self.id, self.class.hash_salt)
HashidsRails.hide(self.id, self.class.hash_salt, self.class.min_hash_length)
end

# Override ActiveRecord::Persistence#reload
Expand Down