Module: OccamsRecord::Ugly

Defined in:
lib/occams-record/ugly.rb

Overview

This module contains helpers for things you shouldn’t, but sometimes must, do in legacy codebases.

Class Method Summary collapse

Class Method Details

.active_record(model, record) ⇒ ActiveRecord::Base

Loads an Occams Record object into an ActiveRecord model. THIS WILL NEGATE ALL PERFORMANCE IMPROVEMENTS! The ONLY reason to use this is if you absolutely need ActiveRecord objects but still want to use Occams’s more advanced eager loading or find_each/find_in_batches features.

OccamsRecord
  .query(Order.order("created_at DESC"))
  .eager_load(:line_items, ->(q) { q.order("price") })
  .find_each do |o|
    order = OccamsRecord::Ugly.active_record(o)
    ...
  end

Parameters:

  • model (ActiveRecord::Base)

    The model to load the record into

  • record (OccamsRecord::Result::Row)

    The OccamsRecord row

Returns:

  • (ActiveRecord::Base)


23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/occams-record/ugly.rb', line 23

def self.active_record(model, record)
  active = model.new(record.to_h)

  record.class.associations.each do |assoc_name|
    assoc = active.class.reflections[assoc_name]
    obj = record.send assoc_name
    next if assoc.nil? or obj.nil?

    if obj.is_a? Array
      active.send(assoc_name).load_target.replace obj.map { |x|
        active_record(assoc.klass, x)
      }
    else
      active.send "#{assoc_name}=", active_record(assoc.klass, obj)
    end
  end

  active
end