user4965201
user4965201

Reputation: 973

Add a random string while updating attribute

I am looking for a method that can generate a random string in the starting of the email field while updating the record.

def update
  @user = User.find_by_id(4)
  @user.email = #method to update email with random string
end

So if I have the email record [email protected] and I want to update it like this:

[email protected]

How it can be done in rails?

Upvotes: 0

Views: 246

Answers (5)

Yury Lebedev
Yury Lebedev

Reputation: 4015

You can use the SecureRandom library:

@user.email = "#{SecureRandom.hex(10)}_#{user.email}"

Upvotes: 4

Amit Sharma
Amit Sharma

Reputation: 3477

I hope this will help you.

def update
  @user = User.find_by_id(4)
  @user.email = "#{generate_random_string(8)}_#{@user.email}"
  ## You can pass any length to generate_random_string method, in this I have passed 8.
end

private

def generate_random_string(length)
  options = { :length => length.to_i, :chars => ('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a }
  Array.new(options[:length]) { options[:chars].to_a[rand(options[:chars].to_a.size)] }.join
end

Upvotes: -1

Nitin
Nitin

Reputation: 7366

create an action in your application controller like this :

private 
  def generate_random_string
    SecureRandom.urlsafe_base64(nil, false)
  end

And use it like this in any controller you want:

def update
  @user = User.find_by_id(4)
  @user.email = generate_random_string + @user.email
end

Upvotes: -1

Dushyant
Dushyant

Reputation: 4960

Why not use SecureRandom?

require 'securerandom'
random_string = SecureRandom.hex # provide argument to limit the no. of characters

# outputs: 5b5cd0da3121fc53b4bc84d0c8af2e81 (i.e. 32 chars of 0..9, a..f)

For appending before email, you can do something like

@user.email = "#{SecureRandom.hex(5))_#{@user.email}" # 5 is no. of characters

Hope it helps!

Upvotes: 2

Vrushali Pawar
Vrushali Pawar

Reputation: 3803

(1..8).map{|i| ('a'..'z').to_a[rand(26)]}.join

8 is the number of characters you want to generate randomly.

Upvotes: 1

Related Questions