From 23c01ba1a0ebd95ce2b2e86f6b664610f191e9e8 Mon Sep 17 00:00:00 2001 From: Delon Newman Date: Wed, 9 Oct 2024 14:44:25 -0400 Subject: [PATCH] Simplify unique name --- app/models/dragnet/survey/name.rb | 2 +- app/models/dragnet/unique_name.rb | 19 ++++++++----------- 2 files changed, 9 insertions(+), 12 deletions(-) diff --git a/app/models/dragnet/survey/name.rb b/app/models/dragnet/survey/name.rb index 8ccfbd3..43e4724 100644 --- a/app/models/dragnet/survey/name.rb +++ b/app/models/dragnet/survey/name.rb @@ -2,7 +2,7 @@ module Dragnet module Survey::Name def self.assign!(survey) name = unique_name(survey) - survey.name = name.to_s if name.generate? + survey.name = name.as_name if name.generate? survey.slug = name.as_slug if name.generate? || assign_slug?(survey) end diff --git a/app/models/dragnet/unique_name.rb b/app/models/dragnet/unique_name.rb index 2a39726..08ed291 100644 --- a/app/models/dragnet/unique_name.rb +++ b/app/models/dragnet/unique_name.rb @@ -2,19 +2,20 @@ module Dragnet class UniqueName - def initialize(record, attribute: :name, scope: nil, root_name: "New #{record.class.model_name.human}") + def initialize(record, scope: nil) @record = record - @attribute = attribute - @root_name = root_name + @root_name = "New #{record.class.model_name.human}" @scope_attribute = scope end def as_slug + return @record.slug if @record.slug.present? && !generate? + Utils.slug(as_name) end def as_name - return record_name unless generate? + return @record.name unless generate? generate end @@ -38,11 +39,7 @@ def scope_attribute_will_change? end def auto_named? - record_name.start_with?(@root_name) - end - - def record_name - @record.public_send(@attribute) + @record.name.start_with?(@root_name) end def duplicated_root? @@ -55,8 +52,8 @@ def unique_root? def auto_named_count model = @record.class - field = model.arel_table[@attribute] - query = model.where(@attribute => @root_name).or(model.where(field.matches("#{@root_name} (%)"))) + field = model.arel_table[:name] + query = model.where(name: @root_name).or(model.where(field.matches("#{@root_name} (%)"))) return query.count unless @scope_attribute query.where(@scope_attribute => record_scope_value).count