Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generate uuid after initialize to support validations on id #16

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions lib/activeuuid/uuid.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
24 changes: 23 additions & 1 deletion spec/lib/activerecord_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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] }
Expand Down Expand Up @@ -184,4 +206,4 @@
end
end
end
end
end
4 changes: 4 additions & 0 deletions spec/support/models/uuid_article.rb
Original file line number Diff line number Diff line change
@@ -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