Created
March 5, 2013 20:38
-
-
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?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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