Skip to content

Commit

Permalink
Contestant 2: ID is a nice custom string
Browse files Browse the repository at this point in the history
  • Loading branch information
ikapelyukhin committed Jan 31, 2018
1 parent 6e05762 commit feac2d8
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 6 deletions.
11 changes: 11 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 Down Expand Up @@ -42,6 +43,16 @@ def change_mirroring!(mirroring_enabled)

private

def set_unique_id
self.unique_id = generate_unique_id if (custom? && !unique_id)
end

def generate_unique_id
last_repo = Repository.where(custom: true).order('length(unique_id), unique_id asc').last
return 'c1' unless last_repo
'c' + (last_repo.unique_id.gsub(/\D/, '').to_i + 1).to_s
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
16 changes: 16 additions & 0 deletions spec/models/repository_spec.rb
Expand Up @@ -55,4 +55,20 @@
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
let(:repo1) { create :repository, :custom, external_url: 'http://example.com/test1/' }
let(:repo2) { create :repository, :custom, external_url: 'http://example.com/test2/' }
let(:repo3) { create :repository, :custom, external_url: 'http://example.com/test3/' }

before do
repo1
repo2.destroy
repo3
end

it('first repo has correct id') { expect(repo1.unique_id).to eq('c1') }
it('second repo has correct id') { expect(repo2.unique_id).to eq('c2') }
it('third repo has correct id after deletion of the second repo') { expect(repo3.unique_id).to eq('c2') }
end
end

0 comments on commit feac2d8

Please sign in to comment.