Skip to content

Commit

Permalink
Add GenerateUrns service
Browse files Browse the repository at this point in the history
This service will create all the available urns per application route.
They will be randomized, unique and the next available urn to be taken
will retreived with the Urn.next method.

Once all the urn are exhausted this method will raise an error and the
format of the URN will need updating ie increase the size of the
suffix set.  Urn::MAX_SUFFIX
  • Loading branch information
fumimowdan committed Sep 27, 2023
1 parent 2db94a3 commit f3162cc
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 0 deletions.
62 changes: 62 additions & 0 deletions app/services/generate_urns.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# Service responsible for the generation of all urns
# It will save the set of available urns based the current URN format
# and store it in the database URNs table.
#
# The Urn model will then be able to fetch the next available unique and
# random urn for application submition
#
# Example:
#
# Urn.next("teacher") # => "IRPTE12345"
# Urn.next("teacher") # => "IRPTE12345"
# Urn.next("salaried_trainee") # => "IRPST12345"
#
class GenerateUrns
def self.call
return if Urn.count.positive? # Do not override the current urn state

Urn.transaction do
Urn::VALID_CODES.each_value do |code|
new(code:).generate
end
end
end

def initialize(code:)
@code = code
end

attr_reader :code

def generate
data = unused_urns.map do |suffix|
{ prefix: Urn::PREFIX, code: code, suffix: suffix }
end
Urn.insert_all(data) # rubocop:disable Rails/SkipsModelValidations
end

private

def unused_urns
generate_suffixes - existing_suffixes
end

def generate_suffixes
Array
.new(Urn::MAX_SUFFIX) { _1 }
.drop(1)
.shuffle!
end

def existing_suffixes
route = Urn::VALID_CODES.key(code)
Application
.where(application_route: route)
.pluck(:urn)
.map { extract_suffix(_1) }
end

def extract_suffix(urn)
urn.match(/\d+/)[0].to_i
end
end
13 changes: 13 additions & 0 deletions spec/services/generate_urns_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
require "rails_helper"

RSpec.describe GenerateUrns do
subject(:service) { described_class }

describe ".call" do
it { fail }
end

describe ".generate" do
it { fail }
end
end

0 comments on commit f3162cc

Please sign in to comment.