Skip to content

Commit

Permalink
Simplify unique name
Browse files Browse the repository at this point in the history
  • Loading branch information
delonnewman committed Oct 9, 2024
1 parent 8b883ca commit 23c01ba
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 12 deletions.
2 changes: 1 addition & 1 deletion app/models/dragnet/survey/name.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
19 changes: 8 additions & 11 deletions app/models/dragnet/unique_name.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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?
Expand All @@ -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
Expand Down

0 comments on commit 23c01ba

Please sign in to comment.