Module: Snaptime::RelationsBuilder

Defined in:
lib/snaptime/relations_builder.rb

Class Method Summary collapse

Class Method Details

.build_versioned_relation(klass, macro, name, scope = nil, options = {}, &extension) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/snaptime/relations_builder.rb', line 5

def self.build_versioned_relation(klass, macro, name, scope = nil, options = {}, &extension)
  if scope.is_a?(Hash)
    options = scope
    scope   = nil
  end

  options[:primary_key] ||= (klass.versioned? ? :natural_id : klass.primary_key)

  versioned_scope = proc do
    rel = spawn.unscope(where: %i(valid_from valid_to))
    rel = rel.merge(scope) unless scope.nil?
    rel._at_explicit_snaptime(Snaptime.snaptime)
  end

  klass.send(macro, name, versioned_scope, options, &extension)

  reflection = klass.reflect_on_association(name)

  unless reflection.klass.versioned?
    fail Exceptions::AssociationTargetNotVersioned, reflection.klass
  end

  klass.versioned_associations = klass.versioned_associations.merge(
    name => reflection
  )
end