Skip to content

Instantly share code, notes, and snippets.

@rafaelp
Created June 8, 2011 14:22
Show Gist options
  • Save rafaelp/1014508 to your computer and use it in GitHub Desktop.
Save rafaelp/1014508 to your computer and use it in GitHub Desktop.
How to avoid duplicate entries on self generated hash (edit_code in this example)
# model
before_create :set_edit_code
def self.friendly_token
ActiveSupport::SecureRandom.hex(10)
end
def self.edit_code_exists?(edit_code)
!where(:edit_code => edit_code).first.nil?
end
def set_edit_code
loop do
self.edit_code = self.class.friendly_token
break self.edit_code unless self.class.edit_code_exists?(self.edit_code)
end
end
# rspec
describe "#edit_code" do
before(:each) do
@idea = Idea.new(valid_attributes)
end
context "before create" do
it "should set edit code" do
expect {
@idea.save
}.should change(@idea, :edit_code).from(nil)
@idea.edit_code.length.should == 20
end
it "should avoid same token" do
@idea.save
@idea.update_attribute(:edit_code, 'first-hash')
Idea.should_receive(:friendly_token).and_return('first-hash', 'second-hash')
@new_idea = Idea.new(valid_attributes)
@new_idea.save
@new_idea.edit_code.should == 'second-hash'
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment