Module: Orphanage::Methods

Defined in:
lib/orphanage.rb

Overview

self.included

Instance Method Summary collapse

Instance Method Details

#adopt(fks, options = {}) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/orphanage.rb', line 10

def adopt fks, options={}
  # creates a new record in the home table. Returns the created record
  # fks(hash) mapping of foreign keys to values.
  # options(hash): optionally override adoption options set in class

  default_options = self.class.adopt_options
  merged_options = default_options.deep_merge options
  dest = merged_options[:home] # the destination model

  # columns allowed in the destination model
  allowed_cols = dest.column_names
  allowed_cols.delete "id" # obviously this shouldn't carry over

  # timestamps that shouldn't be carried over in the adption
  timestamps_to_remove = merged_options[:update_timestamps]
                          .select{|k, v| v}
                          .map{|k, v| "#{k.to_s}_at" }

  allowed_cols = allowed_cols - timestamps_to_remove

  record = dest.new self
                  .attributes
                  .select {|k, v| allowed_cols.include? k}

  dest.transaction do
    record.update_attributes!(fks)
    self.destroy! if merged_options[:destroy_on_adopt]
  end

  return record

end