Class: LazyGlobalRecord
- Inherits:
-
Object
- Object
- LazyGlobalRecord
- 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
- #creatable? ⇒ Boolean
-
#initialize(relation:, filter: nil, create_with: nil, resettable: true, creatable: !Rails.env.production?)) ⇒ LazyGlobalRecord
constructor
A new instance of LazyGlobalRecord.
- #reload ⇒ Object
- #reset ⇒ Object
- #resettable? ⇒ Boolean
- #value ⇒ Object
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_all ⇒ Object
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_all ⇒ Object
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
59 60 61 |
# File 'lib/lazy_global_record.rb', line 59 def creatable? !!@creatable end |
#reload ⇒ Object
68 69 70 71 |
# File 'lib/lazy_global_record.rb', line 68 def reload reset value end |
#reset ⇒ Object
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
55 56 57 |
# File 'lib/lazy_global_record.rb', line 55 def resettable? !!@resettable end |
#value ⇒ Object
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 |