0

I want to auto generate a hash value from within the model.

The user creates a resume, they then have the option to share it by clicking a share button which auto generates a unique (random hashed string) url tied to that specific resumes view.

class ResumesController < ApplicationController

  def share
    @resume = Resume.find(params[:id])

    @share = Share.new
    @share.resume_id = @resume.id 

    @share.save

    redirect_to action: 'index'
  end

end

My Share model has two columns, resume_id, which I already set in the controller, andhash_url` which I want to automatically set in the model.

class Share < ActiveRecord::Base
  attr_accessible :label, :resume_id, :url

end

My question is, how do I go about creating a unique hash and store it in the hash_url column? Also, I'm assuming before it saves it will have to check the share table to make sure it is not saving a hash that already exists.

tereško
  • 58,060
  • 25
  • 98
  • 150
zhs
  • 69
  • 1
  • 10

2 Answers2

0

You can generate and store a hash before saving the object. Add something like this to your model:

# share.rb
before_validation :generate_hash

private
def generate_hash
  self.hash_url = Resume.find(resume_id).content.hash
end

The hash method is a method Ruby provides: http://ruby-doc.org/core-2.1.1/String.html#method-i-hash It returns a hash based on the string's length and content.

spickermann
  • 100,941
  • 9
  • 101
  • 131
  • Awesome! but there isn't anything in that Resume that I need to find and hash. I just need to generate a random hash (maybe I could limit how many characters it is) and assign that as the self.hash_url. So not sure if it would have to call another function that generates that hash? – zhs Aug 08 '14 at 23:28
  • I understood that you want an hash depending on the content of our resume, so that when two resumes have the same content they also have the same hash. If you just need a unique value, use `self.hash_url = SecureRandom.hex` or an other method from the `SecureRandom` module: http://ruby-doc.org/stdlib-2.1.1/libdoc/securerandom/rdoc/SecureRandom.html – spickermann Aug 08 '14 at 23:54
0

before_create

I'm guessing you want to send users to the likes of:

domain.com/resumes/your_secret_hash_url #-> kind of like a uuid?

The way I would do this is to use the before_create callback with SecureRandom. Whilst this won't give you a unique value, you can check it against the form:

#app/models/resume.rb
Class Resume < ActiveRecord::Base
   before_create :set_hash

   private

   def set_hash
       self.hash_url = loop do
         random_token = SecureRandom.urlsafe_base64(nil, false)
         break random_token unless Resume.exists?(token: random_token)
       end
   end
end

Reference: Best way to create unique token in Rails?

This will give you the ability to set the hash_url on create, and have it be unique

Community
  • 1
  • 1
Richard Peck
  • 76,116
  • 9
  • 93
  • 147