Skip to content

Instantly share code, notes, and snippets.

@brianjlandau
Created July 22, 2010 19:31
Show Gist options
  • Select an option

  • Save brianjlandau/486461 to your computer and use it in GitHub Desktop.

Select an option

Save brianjlandau/486461 to your computer and use it in GitHub Desktop.
ActiveRecord mixin to create a name for a duplicate object when names need to be unique.
module Duplicatable
def duplicate_name(no_spaces = false)
new_name = no_spaces ? "#{self.name}_Copy" : "#{self.name} Copy"
replace_name = no_spaces ? "#{new_name}_" : "#{new_name} "
find_options = {:conditions => ["name LIKE ?", "#{new_name}%"],
:order => "copy_number DESC",
:select => "id, CAST(REPLACE(name, '#{replace_name}', '') AS UNSIGNED INTEGER) AS copy_number"}
last_copy = self.class.respond_to?(:find_with_deleted) ?
self.class.find_with_deleted(:first, find_options) :
self.class.first(find_options)
if last_copy
copy_number = last_copy.copy_number.try(:to_i) || 1
new_name = no_spaces ? "#{new_name}_#{copy_number + 1}" : "#{new_name} #{copy_number + 1}"
end
new_name
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment