Skip to content

Commit

Permalink
Wrap Urn method next in fiber block
Browse files Browse the repository at this point in the history
To protect against FiberError
  • Loading branch information
fumimowdan committed Oct 24, 2023
1 parent 3cfc72b commit cd22564
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 6 deletions.
25 changes: 20 additions & 5 deletions app/models/urn.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,11 @@ def initialize
teacher: "TE",
salaried_trainee: "ST",
}.with_indifferent_access
@default_urns = ->(_) { [] }
@default_urns = { teacher: [], salaried_trainee: [] }.with_indifferent_access
@default_existing_urns = -> { [] }
end

attr_writer :prefix, :codes, :max_suffix, :seeds, :urns, :padding_size
attr_writer :prefix, :codes, :max_suffix, :seeds, :existing_urns, :padding_size

def prefix
@prefix || @default_prefix
Expand All @@ -53,7 +54,11 @@ def seeds
end

def urns
@urns || @default_urns
(@urns || @default_urns).with_indifferent_access
end

def existing_urns
@existing_urns || @default_existing_urns
end
end

Expand All @@ -69,19 +74,29 @@ def config
end

def next(route)
routes[route].next
Fiber.new { routes[route].next }.resume
rescue KeyError
raise(ArgumentError, "Invalid route: #{route}, must be one of #{config.codes.keys}")
end

def load_existing_urns
return @urns if @urns

data = config.existing_urns.call
@urns = data.each_with_object(config.urns) do |(route, urn), hash|
hash[route] << urn
hash
end
end

private

def routes
@routes ||= Concurrent::Hash.new do |hash, route|
hash[route] = urn_enumerator(
config.codes.fetch(route),
config.seeds.fetch(route, Random.new_seed),
config.urns.call(route),
config.urns.fetch(route),
)
end
end
Expand Down
1 change: 1 addition & 0 deletions app/services/submit_form.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ def success?
end

def submit_form!
Urn.load_existing_urns
create_application_records
send_applicant_email
@success = true
Expand Down
2 changes: 1 addition & 1 deletion config/initializers/urn.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@
Urn.configure do |c|
c.prefix = "IRP"
c.max_suffix = 99_999
c.urns = ->(route) { Application.where(application_route: route).pluck(:urn) }
c.existing_urns = -> { Application.group(:application_route, :urn).pluck(:application_route, :urn) }
end

0 comments on commit cd22564

Please sign in to comment.