0

Hi :) I have a question I'm not really sure how to fix or solve the specific problem.

I am using MongoDB .

I would like to make my route small to share it to the public.

For example

https://example.com/api/v1/users/:user_id/pictures/:picture_id

To

https://example.com/aghu234

Because I don't want that other users see the how path. I hope you guys can help me :)

BilalReffas
  • 8,132
  • 4
  • 50
  • 71
  • We call that using a "slug"... which will probably help you google for examples by other people... eg: http://stackoverflow.com/questions/31059992/ruby-on-rails-resource-routes-use-slug-instead-of-id – Taryn East Aug 14 '16 at 23:25
  • 1
    Good luck! if you get stuck on any particular implementation, come back and we'll help you with that :) – Taryn East Aug 14 '16 at 23:52
  • Do you maybe know how to start with that ? I am really new with backend development:/ This is how my route look https://example.com/api/v1/users/:user_id/pictures/:picture_id. I just want to access to the object picture with a friendly id. Like https://example.com/agdh675. I would be really happy if you can help me with a small introduction I am using mongoid as well – BilalReffas Aug 15 '16 at 02:32
  • The link to the other stack overflow question has examples of the code you will start with in its answers :) – Taryn East Aug 15 '16 at 04:28

2 Answers2

2

You could use the shortener gem, which does exactly what you're asking for.

DaniG2k
  • 4,772
  • 36
  • 77
2

You can use shortener gem, but there is no fun in using 3rd party gems. So, If you want in-house version then you can use following sample code.

ALLOWED_CHARACTER_SPACE = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".split(//)
def convert_uid_to_short(uid)
        surl = ''
        base = ALLOWED_CHARACTER_SPACE.length
        while uid > 0
            surl << ALLOWED_CHARACTER_SPACE[uid.modulo(base)]
            uid /= base
        end
        surl.reverse
    end

In above method, you have pass uid, a unique identifier in integer format for your url/api. It will return a short url for the unique identifier. You can then use the short version in your code appropriately.

Sample:

convert_uid_to_short(10)
output: k

convert_uid_to_short(1043234)
output: exyw
Abhishek
  • 6,912
  • 14
  • 59
  • 85