Module: ActsAsReplaceable::InstanceMethods

Defined in:
lib/acts_as_replaceable/acts_as_replaceable.rb

Instance Method Summary collapse

Instance Method Details

#_create_record(*args) ⇒ Object

Override the create or update method so we can run callbacks, but opt not to save if we don’t need to



146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/acts_as_replaceable/acts_as_replaceable.rb', line 146

def _create_record(*args)
  ActsAsReplaceable::HelperMethods.lock_if(ActsAsReplaceable.concurrency, self) do
    find_and_replace
    if @has_not_changed
      logger.info "(acts_as_replaceable) Found unchanged #{self.class.to_s} ##{id} #{"- Name: #{name}" if respond_to?('name')}"
    elsif @has_been_replaced
      _update_record(*args)
      logger.info "(acts_as_replaceable) Updated existing #{self.class.to_s} ##{id} #{"- Name: #{name}" if respond_to?('name')}"
    else
      super
      logger.info "(acts_as_replaceable) Created #{self.class.to_s} ##{id} #{"- Name: #{name}" if respond_to?('name')}"
    end
  end

  return true
end

#find_and_replaceObject

Replaces self with an existing copy from the database if available, raises an exception if more than one copy exists in the database



164
165
166
167
168
169
170
171
172
# File 'lib/acts_as_replaceable/acts_as_replaceable.rb', line 164

def find_and_replace
  existing = ActsAsReplaceable::HelperMethods.find_existing(self)

  if existing.length > 1
    raise RecordNotUnique, "#{existing.length} duplicate #{self.class.model_name.human.pluralize} present in database"
  end

  replace_with(existing.first) if existing.first
end

#replace_with(existing) ⇒ Object



174
175
176
177
178
179
180
181
# File 'lib/acts_as_replaceable/acts_as_replaceable.rb', line 174

def replace_with(existing)
  # Inherit target's attributes for those in acts_as_replaceable_options[:inherit]
  ActsAsReplaceable::HelperMethods.copy_attributes(acts_as_replaceable_options[:inherit], existing, self)

  @new_record        = false
  @has_been_replaced = true
  @has_not_changed   = !ActsAsReplaceable::HelperMethods.mark_changes(self, existing)
end