Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

Generate uuid after initialize to support validations on id #16

Open
wants to merge 2 commits into from

3 participants

@thetamind

Generate the uuid during after_initialize instead of before_create as suggested in #6. This enables validation of id or other uuid attributes.

@jashmenn
Owner

cool ill take a look at this shortly.

@jashmenn
Owner

@thetamind - this looks like a good change, however we've changed the way we're testing a bit so the merge fails. Could you update the commit to match the current testing structure? Then I'll merge in the after_initialize change.

@pyromaniac
Collaborator

Dude, Can you rebase your patch please, or I'll do it )

@pyromaniac
Collaborator

I tried to implement this on top of master, but my specs failed because of after_initialize - reload with fields specified is not working.
Also I've recall why I did not do this after_initialize - it is not default AR behavior, the default is to ask for id after_create, so I've make it compatible. I have no any idea, why do you need to validate id before creation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
This page is out of date. Refresh to see the latest.
View
1  lib/activeuuid/uuid.rb
@@ -86,6 +86,7 @@ module UUID
singleton_class.alias_method_chain :instantiate, :uuid
before_create :generate_uuids_if_needed
+ after_initialize :generate_uuids_if_needed
end
module ClassMethods
View
24 spec/lib/activerecord_spec.rb
@@ -96,6 +96,28 @@
let(:model) { described_class }
subject { model }
+ context 'new record' do
+ let!(:article) { Fabricate.build :uuid_article }
+ subject { article }
+ let(:uuid) { UUIDTools::UUID.random_create }
+ let(:string) { uuid.to_s }
+ before { subject.another_uuid = string }
+
+ context 'validation' do
+ its(:id) { should be_nil }
+ its(:another_uuid) { should be_a UUIDTools::UUID }
+ specify { subject.should be_new_record }
+ specify { subject.should be_valid }
+ end
+
+ context 'save without validation' do
+ before { subject.save(validate: false) }
+
+ its(:id) { should be_a UUIDTools::UUID }
+ specify { subject.should be_valid }
+ end
+ end
+
context 'model' do
its(:primary_key) { should == 'id' }
its(:all) { should == [article] }
@@ -184,4 +206,4 @@
end
end
end
-end
+end
View
4 spec/support/models/uuid_article.rb
@@ -1,3 +1,7 @@
class UuidArticle < ActiveRecord::Base
include ActiveUUID::UUID
+
+ validates :id, presence: true, uniqueness: true, length: { in: 32..40 }, unless: :new_record?
+ validates :another_uuid, presence: true, uniqueness: true, length: { in: 32..40 }, unless: :new_record?
+
end
Something went wrong with that request. Please try again.