Skip to content

Commit

Permalink
Handle re-ranking failure by aborting the save with error
Browse files Browse the repository at this point in the history
  • Loading branch information
bf4 committed Jul 23, 2019
1 parent b3550b4 commit a66051b
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 5 deletions.
24 changes: 23 additions & 1 deletion lib/ranked-model.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,33 @@ def self.included base
private

def handle_ranking
@ranking_succeeded = true
self.class.rankers.each do |ranker|
ranker.with(self).handle_ranking
ranking_failed_reason = catch :ranking_failed do
ranker.with(self).handle_ranking
end
handle_ranking_failure(ranker, ranking_failed_reason)
end
@ranking_succeeded
end

def handle_ranking_failure(ranker, ranking_failed_reason)
return if ranking_failed_reason.nil?
errors.add ranker.column, ranking_failed_reason
@ranking_succeeded = false
abort_handle_ranking
end

if defined?(Rails) && Rails.version >= '5'
def abort_handle_ranking
throw :abort
end
else
def abort_handle_ranking
end
end


module ClassMethods

def ranker name
Expand Down
7 changes: 3 additions & 4 deletions lib/ranked-model/ranker.rb
Original file line number Diff line number Diff line change
Expand Up @@ -185,10 +185,10 @@ def rearrange_ranks
_scope = finder
escaped_column = instance_class.ranker_connection_class.connection.quote_column_name ranker.column
if current_first.nil?
return if handle_cannot_rearrange_ranks("current_first is nil").nil?
return if handle_cannot_rearrange_ranks("current_first not found").nil?
end
if current_last.nil?
return if handle_cannot_rearrange_ranks("current_last is nil").nil?
return if handle_cannot_rearrange_ranks("current_last not found").nil?
end
# If there is room at the bottom of the list and we're added to the very top of the list...
if current_first.rank && current_first.rank > RankedModel::MIN_RANK_VALUE && rank == RankedModel::MAX_RANK_VALUE
Expand All @@ -215,8 +215,7 @@ def rearrange_ranks
end

def handle_cannot_rearrange_ranks(message)
logger.warn "[RANKED_MODEL] #{message}. Skipping re-ranking of #{instance.model_name.name} #{instance.id}"
nil
throw :ranking_failed, "Could not re-rank: #{message}."
end

def rebalance_ranks
Expand Down

0 comments on commit a66051b

Please sign in to comment.