Search code examples
ruby-on-rails-3clone

Ruby/Rails unique name generator


I have a User model which has_many Documents. Each Document's title must be unique within the scope of a User. This works as expected.

class Document < ActiveRecord::Base
  has_many :documents, :dependent => :delete_all
end

class Document < ActiveRecord::Base
  belongs_to :user
  validates_presence_of :title
  validates_uniqueness_of :title, :scope => :user_id
end

When I clone a Document, I want to ensure that its title is unique. OSX will append 'copy' to an document that is copied in Finder. If the object's name ends with 'copy', it will add an incremented numerical value, starting with 2 (e.g. 'foo copy 2'). I would like to reproduce this behavior.

It seems like I would need to do the following in the ResumeController's copy action:

  1. get the User's document collection
  2. extract the titles to an array
  3. search the array for the new object's title
  4. if the title isn't found, save the object
  5. if the title is found (could be mulitple, like 'foo Copy', 'foo Copy 2'), append 'Copy' to the end of the title or increment the number. The regex pattern 'Copy[ 0-9]*$' seems to locate a correct match.

At the moment, the copy logic is in the ResumeController, but it seems more appropriate to add it to the Document model.

Any advice is appreciated.


Solution

  • I decided that the easiest solution was simply to add 'copy YYYYMMDDHHMMSS' to the end of the file's name, where 'YYYYMMDDHHMMSS' is replaced by a date-time value.