Class: LazyGlobalRecord

Inherits:
Object
  • Object
show all
Defined in:
lib/lazy_global_record.rb,
lib/lazy_global_record/version.rb

Constant Summary collapse

FROZEN_MODEL =

Filter you can use if you really want to do this – not sure how safe it is for AR to share a model between threads even if it is frozen and readonly!, use at your own risk.

->(obj) { obj.tap { |o| o.readonly! }.tap { |o| o.freeze } }
VERSION =
"1.2.0"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(relation:, filter: nil, create_with: nil, resettable: true, creatable: !Rails.env.production?)) ⇒ LazyGlobalRecord

Returns a new instance of LazyGlobalRecord.



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

def initialize( relation:,
                filter: nil,
                create_with: nil,
                resettable: true,
                creatable: !Rails.env.production?)

  @resettable     = resettable
  @creatable      = creatable
  @relation_proc  = relation
  @filter         = filter || lambda { |record| record.id }
  @create_proc    = create_with || lambda { @relation_proc.call.reset.create! }

  @slot = Concurrent::AtomicReference.new
  @slot.set( create_delay )

  self.freeze

  self.class.register(self)
end

Class Method Details

.register(instance) ⇒ Object



7
8
9
# File 'lib/lazy_global_record.rb', line 7

def register(instance)
  @all_instances.push instance
end

.reload_allObject



13
14
15
# File 'lib/lazy_global_record.rb', line 13

def reload_all
  @all_instances.each { |instance| instance.reload if instance.resettable? }
end

.reset_allObject



10
11
12
# File 'lib/lazy_global_record.rb', line 10

def reset_all
  @all_instances.each { |instance| instance.reset if instance.resettable? }
end

Instance Method Details

#creatable?Boolean

Returns:

  • (Boolean)


59
60
61
# File 'lib/lazy_global_record.rb', line 59

def creatable?
  !!@creatable
end

#reloadObject



68
69
70
71
# File 'lib/lazy_global_record.rb', line 68

def reload
  reset
  value
end

#resetObject

Raises:

  • (TypeError)


63
64
65
66
# File 'lib/lazy_global_record.rb', line 63

def reset
  raise TypeError.new("This LazyGlobalRecord object is not resettable") unless resettable?
  @slot.set( create_delay )
end

#resettable?Boolean

Returns:

  • (Boolean)


55
56
57
# File 'lib/lazy_global_record.rb', line 55

def resettable?
  !!@resettable
end

#valueObject



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

def value
  # double-deref, our atomic slot, and the delay itself.
  # needed so we can #reset in a thread-safe way too.
  delay = @slot.value

  value = delay.value
  if delay.reason
    raise delay.reason
  end
  value
end