Module: TemporalTables::RelationExtensions

Defined in:
lib/temporal_tables/relation_extensions.rb

Overview

Stores the time from the “at” field into each of the resulting objects so that it can be carried forward in subsequent queries.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



5
6
7
8
9
# File 'lib/temporal_tables/relation_extensions.rb', line 5

def self.included(base)
	base.class_eval do
		ActiveRecord::Relation::SINGLE_VALUE_METHODS << :at
	end
end

Instance Method Details

#at(*args) ⇒ Object



29
30
31
# File 'lib/temporal_tables/relation_extensions.rb', line 29

def at(*args)
	spawn.at!(*args)
end

#at!(value) ⇒ Object



33
34
35
36
# File 'lib/temporal_tables/relation_extensions.rb', line 33

def at!(value)
	self.at_value = value
	self.where!(klass.build_temporal_constraint(value))
end

#at_valueObject



11
12
13
14
15
16
17
18
# File 'lib/temporal_tables/relation_extensions.rb', line 11

def at_value
	case Rails::VERSION::MINOR
	when 0
		@values.fetch(:at, nil) || Thread.current[:at_time]
	else
		get_value(:at) || Thread.current[:at_time]
	end
end

#at_value=(value) ⇒ Object



20
21
22
23
24
25
26
27
# File 'lib/temporal_tables/relation_extensions.rb', line 20

def at_value=(value)
	case Rails::VERSION::MINOR
	when 0
		@values[:at] = value
	else
		set_value(:at, value)
	end
end

#default_value_for(name) ⇒ Object

Only needed for Rails 5.1.x



84
85
86
87
88
89
90
# File 'lib/temporal_tables/relation_extensions.rb', line 84

def default_value_for(name)
	if name == :at
		nil
	else
		super(name)
	end
end

#exec_queriesObject



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/temporal_tables/relation_extensions.rb', line 61

def exec_queries
	# Note that record preloading, like when you specify
	#  MyClass.includes(:associations)
	# happens within this exec_queries call.  That's why we needed to
	# store the at_time in the thread above.
	threadify_at do
		super
	end

	if historical?
		# Store the at value on each record returned
		@records.each do |r|
			r.at_value = at_value
		end
	end
	@records
end

#historical?Boolean

Returns:

  • (Boolean)


79
80
81
# File 'lib/temporal_tables/relation_extensions.rb', line 79

def historical?
	table_name =~ /_h$/i && at_value
end

#limited_ids_for(*args) ⇒ Object



55
56
57
58
59
# File 'lib/temporal_tables/relation_extensions.rb', line 55

def limited_ids_for(*args)
	threadify_at do
		super *args
	end
end

#threadify_atObject



44
45
46
47
48
49
50
51
52
53
# File 'lib/temporal_tables/relation_extensions.rb', line 44

def threadify_at
	if at_value && !Thread.current[:at_time]
		Thread.current[:at_time] = at_value
		result = yield
		Thread.current[:at_time] = nil
	else
		result = yield
	end
	result
end

#to_sql(*args) ⇒ Object



38
39
40
41
42
# File 'lib/temporal_tables/relation_extensions.rb', line 38

def to_sql(*args)
	threadify_at do
		super *args
	end
end