GN.
GN.

Reputation: 9909

friendly_id gem, smaller hash?

Given that my slug candidate is my title, and it is already used, the slug will return something like: my-title-49c9938b-ece5-4175-a4a4-0bb2b0f26a27

Is it possible to have friendly_id return a smaller hash? Like: my-title-705d62eea60a

Upvotes: 2

Views: 216

Answers (1)

Sebastián Palma
Sebastián Palma

Reputation: 33491

In that case you can create your own method, which you can pass then to friendly_id. There you can define what are going to be the combinations that FriendlyId will use in order to assign a unique identifier to your record as a slug.

For example:

friendly_id :column_candidates, use: :slugged

def column_candidates
  [
    :name,
    [:name, :another_column],
    [...more columns combinated as a fallback]
  ]
end

If FriendlyId can't create a unique record (by slug) after every combination of columns in column_candidates is evaluated, then it's going to append a UUID anyway.

You're free to add the objects you want to column_candidates, being strings, procs, lambdas or symbols. Also the method name doesn't have to be exactly that, you can modify it as needed.

As a last resource, and if a unique identifier can't be created, you can rely on creating your own short and always able to not be unique hash using Digest::SHA1:

...
[-> { Digest::SHA1.hexdigest(name).chars.sample(6).join }]

Upvotes: 3

Related Questions