Skip to content

Instantly share code, notes, and snippets.

@justinko
Created March 5, 2013 20:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justinko/5094046 to your computer and use it in GitHub Desktop.
Save justinko/5094046 to your computer and use it in GitHub Desktop.
You need to "clone" an Active Record object. Which one of the examples do you prefer (or comment with your own!) and why?
module Cloning
def clone_record(column: :name)
self.class.create(column => cloned_column_attribute(column))
end
private
def cloned_column_attribute(column)
1.upto(Float::INFINITY) do |clone_number|
column_attribute = public_send(column)
proposed_column_attribute = "#{column_attribute} (Clone #{clone_number})"
return proposed_column_attribute unless self.class.exist?(column => proposed_column_attribute)
end
end
end
class Topic < ActiveRecord::Base
include Cloning
end
topic = Topic.first
topic.clone_record
topic.clone_record(column: :title)
class RecordCloning
def initialize(record, column: :name)
@record = record
@column = column
end
def clone_record
@record.class.create(@column => cloned_column_attribute)
end
private
def cloned_column_attribute
1.upto(Float::INFINITY) do |clone_number|
return proposed_column_attribute(clone_number) unless taken?(clone_number)
end
end
def taken?(clone_number)
@record.class.exist?(@column => proposed_column_attribute(clone_number))
end
def proposed_column_attribute(clone_number)
"#{column_attribute} (Clone #{clone_number})"
end
def column_attribute
@column_attribute ||= @record.public_send(@column)
end
end
topic = Topic.first
RecordCloning.new(topic).clone_record
RecordCloning.new(topic, column: :title).clone_record
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment