1

I can see from here that has_secure_token can generate a random token for a new record in a (User) model. How can I simply generate a random token without needing to do it for a model? (i.e. suppose an app has no model(s) or to put it really simply, to run some (preferably very simple) method, and it should return a random string like pX27zsMN2ViQKta1bGfLmVJE

I have tried gems SecureRandom and digest as recommended in other answers, but neither seems to bundle install successfully (the SO answers were oldish so perhaps those gems are deprecated?) - I'm using ruby 2.5.1 and rails 5.2.3

My goal is simply to generate tokens to use as keys for an API, so I essentially just need randomly generated strings that are safe to use in urls, perhaps a method that I can specify the length of the token (but I'll take what I can get for now!)

stevec
  • 41,291
  • 27
  • 223
  • 311

1 Answers1

4

Just use SecureRandom. It's not a gem that you have to install. It's built into Ruby:

⇒ ruby -v
ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-darwin18]
⇒ irb
2.5.1 :001 > require 'securerandom'
 => true
2.5.1 :002 > SecureRandom.hex(32)
 => "89d45edb28859a905672b707c8f7599f766d12074584ef48a997230dfc0e0998"
2.5.1 :003 > SecureRandom.base64(12)
 => "KaZbhQ7o7U/f9pMs"
2.5.1 :004 > SecureRandom.uuid
 => "ade17ef5-0943-4c70-b417-df7c96c198cd"
anothermh
  • 9,815
  • 3
  • 33
  • 52
  • For future reference, how can you tell which gems you have to install and which come built in? – stevec May 26 '19 at 07:01
  • 1
    Lots of different ways. You can check the [standard library API](https://ruby-doc.org/stdlib/), the [core API](https://ruby-doc.org/core), and also [here](https://docs.ruby-lang.org/en/2.6.0/). You can look at external resources like [this](https://ruby.fandom.com/wiki/Built-in_classes) and [this](http://phrogz.net/programmingruby/builtins.html), but I don't know if they're up to date. Also see [here](https://stackoverflow.com/q/19151296/3784008). – anothermh May 26 '19 at 07:09