acts_as_hashids

0.2.0last stable release 2 years ago
Complexity Score
Low
Open Issues
0
Dependent Projects
0
Weekly Downloadsglobal
180

License

  • MIT
    • Yesattribution
    • Permissivelinking
    • Permissivedistribution
    • Permissivemodification
    • Nopatent grant
    • Yesprivate use
    • Permissivesublicensing
    • Notrademark grant

Downloads

Readme

acts_as_hashids

Use Hashids (a.k.a. Youtube-Like ID) in ActiveRecord seamlessly.

Installation

Add the acts_as_hashids gem to your Gemfile.

gem "acts_as_hashids"

And run bundle install.

Usage

Activate the function in any model of ActiveRecord::Base.

class Foo < ActiveRecord::Base
  acts_as_hashids
end

foo = Foo.create
# => #<Foo:0x007feb5978a7c0 id: 3>

foo.to_param
# => "ePQgabdg"

Foo.find(3)
# => #<Foo:0x007feb5978a7c0 id: 3>

Foo.find("ePQgabdg")
# => #<Foo:0x007feb5978a7c0 id: 3>

Foo.with_hashids("ePQgabdg").first
# => #<Foo:0x007feb5978a7c0 id: 3>

Use in Rails

Only one thing you need to hash ids is put acts_as_hashids in ApplicationRecord, then you will see hash ids in routes URL and they are handled correctly as long as you use find to find records.

Options

length

You can customize the length of hash ids per model. The default length is 8.

class Foo < ActiveRecord::Base
  acts_as_hashids length: 2
end

Foo.create.to_param
# => "Rx"

secret

You can customize the secret of hash ids per model. The default secret is the class name. The name of base class is used for STI.

class Foo1 < ActiveRecord::Base
  acts_as_hashids secret: 'my secret'
end

class Foo2 < ActiveRecord::Base
  acts_as_hashids secret: 'my secret'
end

Foo1.create.to_param
# => "RxQce3a2"

Foo2.create.to_param
# => "RxQce3a2"

alphabet

Specify which characters you use to generate hashids.

class Foo < ActiveRecord::Base
  acts_as_hashids alphabet: '0123456789uvwxyz'
end

Foo.create(id: 1).to_param
# => "4xw8zwyv"

Test

Execute the command below to run rspec and rubocop.

bundle exec rake

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

Copyright

Copyright (c) 2014 Daisuke Taniwaki. See LICENSE for details.

Dependencies

No runtime dependency information found for this package.

CVE IssuesActive
0
Scorecards Score
No Data
Test Coverage
98.00%
Follows Semver
Yes
Github Stars
78
Dependenciestotal
0
DependenciesOutdated
0
DependenciesDeprecated
0
Threat Modelling
No
Repo Audits
No

Learn how to distribute acts_as_hashids in your own private RubyGems registry

gem install acts_as_hashids
Processing...
Done

10 Releases

RubyGems on Cloudsmith

Getting started with RubyGems on Cloudsmith is fast and easy.