23

I have to generate a unique and random string which is to be stored in database. For doing this I have used the "uuidtools" gem. Then in my controller I have added the following line:

require "uuidtools"

and then in my controllers create method I have declared a 'temp' variable and generating a unique and random 'uuid' string like this:

temp=UUIDTools::UUID.random_create

which is creating a string like this one:

f58b1019-77b0-4d44-a389-b402bb3e6d50

Now my problem is I have to make it short, preferably within 8-10 character. Now how do I do it?? Is it possible to pass any argument to make it a desirable length string??

Thanks in Advance...

Siddharth
  • 833
  • 6
  • 12
  • 25

2 Answers2

52

You don't need uuidtools for this. You can use Secure Random for this.

[1] pry(main)> require "securerandom"
=> true
[2] pry(main)> SecureRandom.hex(20)
=> "82db4d707c4c5db3ebfc349da09c991b7ca0faa1"
[3] pry(main)> SecureRandom.base64(20)
=> "CECjUqNvPBaq0o4OuPy8RvsEoCY="

Passing 4 and 5 to hex will generate 8 and 10 character hex strings respectively.

[5] pry(main)> SecureRandom.hex(4)
=> "a937ec91"
[6] pry(main)> SecureRandom.hex(5)
=> "98605bb20a"
Dogbert
  • 212,659
  • 41
  • 396
  • 397
  • I'm new to rails and Ruby. I tried it with SecureRandom. But actually I couldn't figure it out that how to actually implement this method in my controller. I mean what to be included in my controller and what to download etc. – Siddharth Jan 07 '13 at 12:55
  • 2
    @Siddharth, nothing to download, just add `require 'securerandom'` before you use this method. This is in stdlib of Ruby 1.9.3. – Dogbert Jan 07 '13 at 13:04
  • 8
    SecureRandom actually has a `#uuid` method that generates a RFC 4122-compliant UUID. – Duke Sep 25 '13 at 21:46
  • 4
    One of @Siddharth's requirements was uniqueness. I'm pretty sure the `#hex` and `#base64` methods only guarantee randomness. As @Duke said, `#uuid` is the better choice. – Walking Wiki Sep 03 '15 at 02:40
3

Please see in detail, How I used securerandom in one of my project recently, definitely help you!

create usesguid.rb file in your lib/usesguid.rb and paste below code in that -

require 'securerandom'

module ActiveRecord
  module Usesguid #:nodoc:
    def self.append_features(base)
      super
      base.extend(ClassMethods)  
    end

    module ClassMethods
      def usesguid(options = {})
        class_eval do
          self.primary_key = options[:column] if options[:column]
          after_initialize :create_id
          def create_id
            self.id ||= SecureRandom.uuid
          end
        end
      end
    end
  end
end
ActiveRecord::Base.class_eval do
  include ActiveRecord::Usesguid
end

add following line in your config/application.rb to load file -

require File.dirname(__FILE__) + '/../lib/usesguid'

Create migration script for UUID function as mentioned below to -

class CreateUuidFunction < ActiveRecord::Migration
  def self.up
    execute "create or replace function uuid() returns uuid as 'uuid-ossp', 'uuid_generate_v1' volatile strict language C;"
  end

  def self.down
    execute "drop function uuid();"
  end
end

Here is example for contact migration, how we can use it -

class CreateContacts < ActiveRecord::Migration
  def change
    create_table :contacts, id: false do |t|
      t.column :id, :uuid, null:false 
      t.string :name
      t.string :mobile_no

      t.timestamps
    end
  end
end

Final how to use into your model

class Contact < ActiveRecord::Base
  usesguid

end

This will help you to configure UUID for your rails application.

This can be useful for Rails 3.0, 3.1, 3.2 and 4.0 as well.

Please let me know If you have any issue while using it, so simple!

Rameshwar Vyevhare
  • 2,699
  • 2
  • 28
  • 34