Skip to content

Commit

Permalink
Contestant 3: ID is a short random string
Browse files Browse the repository at this point in the history
  • Loading branch information
ikapelyukhin committed Jan 31, 2018
1 parent 6e05762 commit 0596836
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 6 deletions.
21 changes: 21 additions & 0 deletions app/models/repository.rb
Expand Up @@ -15,6 +15,7 @@ class Repository < ApplicationRecord
validates :local_path, presence: true

before_destroy :ensure_destroy_possible
before_create :set_unique_id

class << self

Expand All @@ -40,8 +41,28 @@ def change_mirroring!(mirroring_enabled)
update_column(:mirroring_enabled, mirroring_enabled)
end

def self.generate_unique_id
(0...5).map { (97 + rand(26)).chr }.join
end

private

def set_unique_id
return unless (custom? && !unique_id)
generated_id = nil
repo = nil

5.times do
generated_id = self.class.generate_unique_id
repo = Repository.find_by(unique_id: generated_id)
break unless repo
end

raise 'Can not generate unique custom repo ID' if repo

self.unique_id = generated_id
end

def ensure_destroy_possible
throw(:abort) unless custom?
end
Expand Down
6 changes: 0 additions & 6 deletions app/services/repository_service.rb
Expand Up @@ -21,12 +21,6 @@ def create_repository!(product, url, attributes, custom: false)
attach_product!(product, repository) unless product.nil?
end

# FIXME: this is a hack to add some not nice ID value
if custom
repository.unique_id = "hack#{repository.id}"
repository.save!
end

repository
end

Expand Down
1 change: 1 addition & 0 deletions spec/factories/repositories.rb
Expand Up @@ -19,6 +19,7 @@

trait :custom do
custom true
unique_id nil
end

trait :with_products do
Expand Down
27 changes: 27 additions & 0 deletions spec/models/repository_spec.rb
Expand Up @@ -55,4 +55,31 @@
it(:handles_subpath) { expect(Repository.make_local_path('http://localhost.com/foo/bar')).to eq('/foo/bar') }
it(:handles_subpath_trailing_slash) { expect(Repository.make_local_path('http://localhost.com/foo/bar/')).to eq('/foo/bar/') }
end

describe '#set_unique_id' do
context 'assigns generated id to the custom repo' do
subject { create :repository, :custom, external_url: 'http://example.com/test1/' }

before do
expect(Repository).to receive(:generate_unique_id).and_return('abcde')
end

its(:unique_id) { is_expected.to eq('abcde') }
end

context "when can't generate the ID" do
let(:first_repo) { create :repository, :custom, external_url: 'http://example.com/test1/' }

before do
expect(Repository).to receive(:generate_unique_id).exactly(6).times.and_return('abcde')
first_repo
end

it 'raises an exception' do
expect do
create :repository, :custom, external_url: 'http://example.com/test2/'
end.to raise_error 'Can not generate unique custom repo ID'
end
end
end
end

0 comments on commit 0596836

Please sign in to comment.