Class: ReactiveRecord::Base
- Inherits:
-
Object
show all
- Extended by:
- LookupTables
- Includes:
- React::IsomorphicHelpers, BackingRecordInspector, Getters, Setters
- Defined in:
- lib/reactive_record/active_record/reactive_record/column_types.rb,
lib/reactive_record/active_record/reactive_record/base.rb,
lib/reactive_record/active_record/reactive_record/dummy_value.rb,
lib/reactive_record/active_record/reactive_record/isomorphic_base.rb
Overview
ActiveRecord column access and conversion helpers
Defined Under Namespace
Classes: DbRequestMade, DummyValue
Class Attribute Summary collapse
Instance Attribute Summary collapse
Class Method Summary
collapse
-
.add_to_outer_scopes(item) ⇒ Object
-
.catch_db_requests(return_val = nil) ⇒ Object
-
.column_type(column_hash) ⇒ Object
-
.data_loading? ⇒ Boolean
While data is being loaded from the server certain internal behaviors need to change for example all record changes are synced as they happen.
-
.default_scope ⇒ Object
-
.define_attribute_methods ⇒ Object
-
.deprecation_warning(model, message) ⇒ Object
-
.destroy_record(model, id, vector, acting_user) ⇒ Object
-
.exists?(model, id) ⇒ Boolean
helper so we can tell if model exists.
-
.find(model, attrs) ⇒ Object
-
.find_record(model, id, vector, save) ⇒ Object
-
.gather_records(records_to_process, force, record_being_saved) ⇒ Object
-
.get_type_hash(record) ⇒ Object
-
.infer_type_from_hash(klass, hash) ⇒ Object
-
.is_enum?(record, key) ⇒ Boolean
-
.load_data(&block) ⇒ Object
-
.load_from_db(record, *vector) ⇒ Object
queue up fetches, and at the end of each rendering cycle fetch the records notify that loads are pending.
-
.load_from_json(json, target = nil) ⇒ Object
-
.new_from_vector(model, aggregate_owner, *vector) ⇒ Object
-
.notify_waiting_for_save(model) ⇒ Object
-
.pre_synchromesh_load_from_db ⇒ Object
-
.save_records(models, associations, acting_user, validate, save) ⇒ Object
-
.schedule_fetch ⇒ Object
-
.serialized? ⇒ Boolean
-
.unscoped ⇒ Object
-
.when_not_saving(model, &block) ⇒ Object
Instance Method Summary
collapse
-
#changed?(*args) ⇒ Boolean
-
#changed_attributes_and_values ⇒ Object
-
#changes ⇒ Object
-
#column_type(attr) ⇒ Object
-
#columns_hash ⇒ Object
-
#convert(attr, val) ⇒ Object
-
#convert_boolean(val) ⇒ Object
-
#convert_date(val) ⇒ Object
-
#convert_datetime(val) ⇒ Object
(also: #convert_time, #convert_timestamp)
-
#convert_float(val) ⇒ Object
(also: #convert_decimal)
-
#convert_integer(val) ⇒ Object
(also: #convert_bigint)
-
#convert_text(val) ⇒ Object
(also: #convert_string)
-
#data_loading? ⇒ Boolean
-
#deprecation_warning(message) ⇒ Object
-
#destroy(&block) ⇒ Object
-
#destroy_associations ⇒ Object
-
#errors ⇒ Object
-
#errors!(hash) ⇒ Object
-
#find(*args) ⇒ Object
-
#get_columns_info_for_vector(vector) ⇒ Object
-
#id ⇒ Object
-
#id=(value) ⇒ Object
-
#initialize(model, hash = {}, ar_instance = nil) ⇒ Base
constructor
-
#initialize_collections ⇒ Object
called when we have a newly created record, to initialize any nil collections to empty arrays.
-
#new? ⇒ Boolean
-
#new_from_vector(*args) ⇒ Object
-
#notify_waiting_for_save ⇒ Object
-
#primary_key ⇒ Object
-
#records ⇒ Object
-
#revert ⇒ Object
-
#save_or_validate(save, validate, force, &block) ⇒ Object
-
#saved!(save_only = nil) ⇒ Object
sets saving to false AND notifies.
-
#saving! ⇒ Object
-
#saving? ⇒ Boolean
-
#send_save_to_server(save, validate, force, &block) ⇒ Object
-
#set_ar_instance! ⇒ Object
-
#sync!(hash = {}) ⇒ Object
sync! now will also initialize any nil collections.
-
#sync_attribute(attribute, value) ⇒ Object
-
#sync_unscoped_collection! ⇒ Object
this keeps the unscoped collection up to date.
class_scopes, clear_waiting_for_save, initialize_lookup_tables, lookup_by_id, lookup_by_object_id, lookup_by_vector, set_id_lookup, set_object_id_lookup, set_vector_lookup, wait_for_save, waiting_for_save
Methods included from Getters
#get_ar_aggregate, #get_attr_value, #get_belongs_to, #get_has_many, #get_non_ar_aggregate, #get_primary_key_value, #get_server_method
Methods included from Setters
#set_ar_aggregate, #set_attr_value, #set_belongs_to, #set_has_many, #set_non_ar_aggregate, #sync_has_many, #update_simple_attribute
#destroyed_details, #dirty_details, #error_details, #inspection_details, #loading_details, #new_details
Constructor Details
#initialize(model, hash = {}, ar_instance = nil) ⇒ Base
Returns a new instance of Base.
141
142
143
144
145
146
147
148
149
150
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 141
def initialize(model, hash = {}, ar_instance = nil)
@model = model
@ar_instance = ar_instance
@synced_attributes = {}
@attributes = {}
@changed_attributes = []
@virgin = true
records[model] << self
Base.set_object_id_lookup(self)
end
|
Class Attribute Details
.current_fetch_id ⇒ Object
Returns the value of attribute current_fetch_id.
130
131
132
|
# File 'lib/reactive_record/active_record/reactive_record/isomorphic_base.rb', line 130
def current_fetch_id
@current_fetch_id
end
|
.outer_scopes ⇒ Object
Returns the value of attribute outer_scopes.
365
366
367
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 365
def outer_scopes
@outer_scopes
end
|
.pending_fetches ⇒ Object
Returns the value of attribute pending_fetches.
129
130
131
|
# File 'lib/reactive_record/active_record/reactive_record/isomorphic_base.rb', line 129
def pending_fetches
@pending_fetches
end
|
.public_columns_hash ⇒ Object
Returns the value of attribute public_columns_hash.
64
65
66
|
# File 'lib/reactive_record/active_record/reactive_record/isomorphic_base.rb', line 64
def public_columns_hash
@public_columns_hash
end
|
Instance Attribute Details
#aggregate_attribute ⇒ Object
Returns the value of attribute aggregate_attribute.
39
40
41
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 39
def aggregate_attribute
@aggregate_attribute
end
|
#aggregate_owner ⇒ Object
Returns the value of attribute aggregate_owner.
38
39
40
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 38
def aggregate_owner
@aggregate_owner
end
|
#ar_instance ⇒ Object
Each method call is either a simple method name or an array in the form [method_name, param, param …] Example [User, [find, 123], todos, active, [due, “1/1/2016”], title] Roughly corresponds to this query: User.find(123).todos.active.due(“1/1/2016”).select(:title)
34
35
36
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 34
def ar_instance
@ar_instance
end
|
#attributes ⇒ Object
Returns the value of attribute attributes.
44
45
46
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 44
def attributes
@attributes
end
|
#changed_attributes ⇒ Object
Returns the value of attribute changed_attributes.
37
38
39
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 37
def changed_attributes
@changed_attributes
end
|
#destroyed ⇒ Object
Returns the value of attribute destroyed.
40
41
42
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 40
def destroyed
@destroyed
end
|
Returns the value of attribute model.
36
37
38
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 36
def model
@model
end
|
#synced_attributes ⇒ Object
Returns the value of attribute synced_attributes.
42
43
44
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 42
def synced_attributes
@synced_attributes
end
|
#updated_during ⇒ Object
Returns the value of attribute updated_during.
41
42
43
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 41
def updated_during
@updated_during
end
|
Returns the value of attribute vector.
35
36
37
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 35
def vector
@vector
end
|
Returns the value of attribute virgin.
43
44
45
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 43
def virgin
@virgin
end
|
Class Method Details
.add_to_outer_scopes(item) ⇒ Object
375
376
377
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 375
def add_to_outer_scopes(item)
@outer_scopes << item
end
|
.catch_db_requests(return_val = nil) ⇒ Object
386
387
388
389
390
391
392
393
394
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 386
def catch_db_requests(return_val = nil)
@catch_db_requests = true
yield
rescue DbRequestMade => e
React::IsomorphicHelpers.log "Warning: request for server side data during scope evaluation: #{e.message}", :warning
return_val
ensure
@catch_db_requests = false
end
|
.column_type(column_hash) ⇒ Object
8
9
10
|
# File 'lib/reactive_record/active_record/reactive_record/column_types.rb', line 8
def self.column_type(column_hash)
column_hash && column_hash[:sql_type_metadata] && column_hash[:sql_type_metadata][:type]
end
|
.data_loading? ⇒ Boolean
While data is being loaded from the server certain internal behaviors need to change for example all record changes are synced as they happen. This is implemented this way so that the ServerDataCache class can use pure active record methods in its implementation
51
52
53
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 51
def self.data_loading?
@data_loading
end
|
.default_scope ⇒ Object
367
368
369
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 367
def default_scope
@class_scopes[:default_scope]
end
|
.define_attribute_methods ⇒ Object
67
68
69
70
71
|
# File 'lib/reactive_record/active_record/reactive_record/isomorphic_base.rb', line 67
def self.define_attribute_methods
public_columns_hash.keys.each do |model|
Object.const_get(model).define_attribute_methods rescue nil
end
end
|
.deprecation_warning(model, message) ⇒ Object
32
33
34
35
36
37
38
39
|
# File 'lib/reactive_record/active_record/reactive_record/isomorphic_base.rb', line 32
def self.deprecation_warning(model, message)
@deprecation_messages ||= []
message = "Warning: Deprecated feature used in #{model}. #{message}"
unless @deprecation_messages.include? message
@deprecation_messages << message
log message, :warning
end
end
|
.destroy_record(model, id, vector, acting_user) ⇒ Object
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
|
# File 'lib/reactive_record/active_record/reactive_record/isomorphic_base.rb', line 557
def self.destroy_record(model, id, vector, acting_user)
model = Object.const_get(model)
record = if id
model.find(id)
else
ServerDataCache.new(acting_user, {})[*vector]
end
record.check_permission_with_acting_user(acting_user, :destroy_permitted?).destroy
{success: true, attributes: {}}
rescue Exception => e
{success: false, record: record, message: e}
end
|
.exists?(model, id) ⇒ Boolean
helper so we can tell if model exists. We need this so we can detect if a record has local changes that are out of sync.
277
278
279
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 277
def self.exists?(model, id)
Base.lookup_by_id(model, id)
end
|
.find(model, attrs) ⇒ Object
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 70
def self.find(model, attrs)
inher_col = model.inheritance_column
if inher_col && model < model.base_class && !attrs.key?(inher_col)
attrs = attrs.merge(inher_col => model.model_name.to_s)
end
model = model.base_class
primary_key = model.primary_key
record =
if (id_to_find = attrs[primary_key])
lookup_by_id(model, id_to_find)
else
@records[model].detect do |r|
!attrs.detect { |attr, value| r.synced_attributes[attr] != value }
end
end
unless record
if !attrs.key?(primary_key) && (id = find_in_db(model, attrs))
record = lookup_by_id(model, id)
attrs = attrs.merge primary_key => id
end
record ||= set_vector_lookup(new(model), [model, [:find_by, attrs]])
attrs.each { |attr, value| record.sync_attribute(attr, value) }
end
record.set_ar_instance!
end
|
.find_record(model, id, vector, save) ⇒ Object
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
|
# File 'lib/reactive_record/active_record/reactive_record/isomorphic_base.rb', line 320
def self.find_record(model, id, vector, save)
if !save
found = vector[1..-1].inject(vector[0]) do |object, method|
if object.nil?
object
elsif method.is_a? Array
if method[0] == 'new'
object.new
else
object.send(*method)
end
elsif method.is_a? String and method[0] == '*'
object[method.gsub(/^\*/,'').to_i]
else
object.send(method)
end
end
if id and (found.nil? or !(found.class <= model) or (found.id and found.id.to_s != id.to_s))
raise "Inconsistent data sent to server - #{model.name}.find(#{id}) != [#{vector}]"
end
found
elsif id
model.find(id)
else
model.new
end
end
|
.gather_records(records_to_process, force, record_being_saved) ⇒ Object
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
|
# File 'lib/reactive_record/active_record/reactive_record/isomorphic_base.rb', line 188
def self.gather_records(records_to_process, force, record_being_saved)
models = []
associations = []
records_to_process = records_to_process.uniq
backing_records = Hash[*records_to_process.collect { |record| [record.object_id, record] }.flatten(1)]
add_new_association = lambda do |record, attribute, assoc_record|
unless backing_records[assoc_record.object_id]
records_to_process << assoc_record
backing_records[assoc_record.object_id] = assoc_record
end
associations << {parent_id: record.object_id, attribute: attribute, child_id: assoc_record.object_id}
end
record_index = 0
while(record_index < records_to_process.count)
record = records_to_process[record_index]
if record.id.loading? and record_being_saved
raise "Attempt to save a model while it or an associated model is still loading: model being saved: #{record_being_saved.model}:#{record_being_saved.id}#{', associated model: '+record.model.to_s if record != record_being_saved}"
end
output_attributes = {record.model.primary_key => record.id.loading? ? nil : record.id}
vector = record.vector || [record.model.model_name.to_s, ["new", record.object_id]]
models << {id: record.object_id, model: record.model.model_name.to_s, attributes: output_attributes, vector: vector}
record.attributes.each do |attribute, value|
if association = record.model.reflect_on_association(attribute)
if association.collection?
[*value.collection, *value.unsaved_children].each do |assoc|
add_new_association.call(record, attribute, assoc.backing_record) if assoc.changed?(association.inverse_of) or assoc.new?
end
elsif record.new? || record.changed?(attribute) || (record == record_being_saved && force)
if value.nil?
output_attributes[attribute] = nil
else
add_new_association.call record, attribute, value.backing_record
end
end
elsif aggregation = record.model.reflect_on_aggregation(attribute) and (aggregation.klass < ActiveRecord::Base)
add_new_association.call record, attribute, value.backing_record unless value.nil?
elsif aggregation
new_value = aggregation.serialize(value)
output_attributes[attribute] = new_value if record.changed?(attribute) or new_value != aggregation.serialize(record.synced_attributes[attribute])
elsif record.new? or record.changed?(attribute)
output_attributes[attribute] = value
end
end if record.new? || record.changed? || (record == record_being_saved && force)
record_index += 1
end
[models.sort_by { |model| model[:id] }, associations, backing_records]
end
|
.get_type_hash(record) ⇒ Object
182
183
184
|
# File 'lib/reactive_record/active_record/reactive_record/isomorphic_base.rb', line 182
def self.get_type_hash(record)
{record.class.inheritance_column => record[record.class.inheritance_column]}
end
|
.infer_type_from_hash(klass, hash) ⇒ Object
352
353
354
355
356
357
358
359
360
361
362
363
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 352
def infer_type_from_hash(klass, hash)
klass = klass.base_class
return klass unless hash
type = hash[klass.inheritance_column]
begin
return Object.const_get(type)
rescue Exception => e
message = "Could not subclass #{klass} as #{type}. Perhaps #{type} class has not been required. Exception: #{e}"
`console.error(#{message})`
end unless !type || type == ''
klass
end
|
.is_enum?(record, key) ⇒ Boolean
349
350
351
|
# File 'lib/reactive_record/active_record/reactive_record/isomorphic_base.rb', line 349
def self.is_enum?(record, key)
record.class.respond_to?(:defined_enums) && record.class.defined_enums[key]
end
|
.load_data(&block) ⇒ Object
59
60
61
62
63
64
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 59
def self.load_data(&block)
current_data_loading, @data_loading = [@data_loading, true]
yield
ensure
@data_loading = current_data_loading
end
|
.load_from_db(record, *vector) ⇒ Object
queue up fetches, and at the end of each rendering cycle fetch the records notify that loads are pending
103
104
105
106
|
# File 'lib/reactive_record/active_record/reactive_record/isomorphic_base.rb', line 103
def load_from_db(*args)
raise DbRequestMade, args if @catch_db_requests
pre_synchromesh_load_from_db(*args)
end
|
.load_from_json(json, target = nil) ⇒ Object
66
67
68
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 66
def self.load_from_json(json, target = nil)
load_data { ServerDataCache.load_from_json(json, target) }
end
|
.new_from_vector(model, aggregate_owner, *vector) ⇒ Object
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 114
def self.new_from_vector(model, aggregate_owner, *vector)
model = model.base_class
record = lookup_by_vector(vector)
unless record
record = new model
set_vector_lookup(record, vector)
end
record.set_ar_instance!
if aggregate_owner
record.aggregate_owner = aggregate_owner
record.aggregate_attribute = vector.last
aggregate_owner.attributes[vector.last] = record.ar_instance
end
record.ar_instance
end
|
.notify_waiting_for_save(model) ⇒ Object
329
330
331
332
333
334
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 329
def self.notify_waiting_for_save(model)
waiters = waiting_for_save(model)
return if waiters.empty? || @records[model].detect(&:saving?)
waiters.each { |waiter| waiter.call model }
clear_waiting_for_save(model)
end
|
.pre_synchromesh_load_from_db ⇒ Object
396
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 396
alias pre_synchromesh_load_from_db load_from_db
|
.save_records(models, associations, acting_user, validate, save) ⇒ Object
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
|
# File 'lib/reactive_record/active_record/reactive_record/isomorphic_base.rb', line 353
def self.save_records(models, associations, acting_user, validate, save)
reactive_records = {}
vectors = {}
new_models = []
saved_models = []
dont_save_list = []
models.each do |model_to_save|
attributes = model_to_save[:attributes]
model = Object.const_get(model_to_save[:model])
id = attributes.delete(model.primary_key) if model.respond_to? :primary_key
vector = model_to_save[:vector]
vector = [vector[0].constantize] + vector[1..-1].collect do |method|
if method.is_a?(Array) and method.first == "find_by_id"
["find", method.last]
else
method
end
end
reactive_records[model_to_save[:id]] = vectors[vector] = record = find_record(model, id, vector, save)
next unless record
if attributes.empty?
dont_save_list << record unless save
elsif record.respond_to?(:id) && record.id
keys = record.attributes.keys
attributes.each do |key, value|
if is_enum?(record, key)
record.send("#{key}=", value)
elsif keys.include? key
record[key] = value
elsif value && (aggregation = record.class.reflect_on_aggregation(key.to_sym)) && !(aggregation.klass < ActiveRecord::Base)
aggregation.mapping.each_with_index do |pair, i|
record[pair.first] = value[i]
end
elsif record.respond_to? "#{key}="
record.send("#{key}=", value)
else
end
end
else
dont_save_list << record unless save
keys = record.attributes.keys
attributes.each do |key, value|
if is_enum?(record, key)
record.send("#{key}=",value)
elsif keys.include? key
record[key] = value
elsif !value.nil? and aggregation = record.class.reflect_on_aggregation(key) and !(aggregation.klass < ActiveRecord::Base)
aggregation.mapping.each_with_index do |pair, i|
record[pair.first] = value[i]
end
elsif key.to_s != "id" and record.respond_to?("#{key}=")
record.send("#{key}=",value)
end
end
new_models << record
end
end
ActiveRecord::Base.transaction do
associations.each do |association|
parent = reactive_records[association[:parent_id]]
next unless parent
if parent.class.reflect_on_aggregation(association[:attribute].to_sym)
aggregate = reactive_records[association[:child_id]]
dont_save_list << aggregate
current_attributes = parent.send(association[:attribute]).attributes
new_attributes = aggregate.attributes
merged_attributes = current_attributes.merge(new_attributes) { |k, current_attr, new_attr| aggregate.send("#{k}_changed?") ? new_attr : current_attr}
aggregate.assign_attributes(merged_attributes)
parent.send("#{association[:attribute]}=", aggregate)
elsif parent.class.reflect_on_association(association[:attribute].to_sym).nil?
raise "Missing association :#{association[:attribute]} for #{parent.class.name}. Was association defined on opal side only?"
elsif parent.class.reflect_on_association(association[:attribute].to_sym).collection?
dont_save_list.delete(parent)
else
parent.send("#{association[:attribute]}=", reactive_records[association[:child_id]])
dont_save_list.delete(parent)
end
end if associations
reactive_records.keep_if do |reactive_record_id, record|
next false unless record
next true if record.frozen?
next true if dont_save_list.include?(record)
next true if record.changed.include?(record.class.primary_key)
next false if record.id && !record.changed?
op = new_models.include?(record) ? :create_permitted? : :update_permitted?
record.check_permission_with_acting_user(acting_user, op).save(validate: false) || true
end
return vectors unless save || validate
all_messages = []
saved_models = reactive_records.collect do |reactive_record_id, model|
messages = model.errors.messages if validate && !model.valid?
all_messages << [model, messages] if save && messages
attributes = model.__hyperloop_secure_attributes(acting_user)
[reactive_record_id, model.class.name, attributes, messages]
end
raise ActiveRecord::Rollback, 'This Rollback is intentional!' unless save
unless all_messages.empty?
::Rails.logger.debug "\033[0;31;1mERROR: HyperModel saving records failed:\033[0;30;21m"
all_messages.each do |model, message|
::Rails.logger.debug "\033[0;31;1m\t#{model}: #{message}\033[0;30;21m"
end
raise 'HyperModel saving records failed!'
end
end
{ success: true, saved_models: saved_models }
rescue Exception => e
if save || validate
{success: false, saved_models: saved_models, message: e}
else
{}
end
end
|
.schedule_fetch ⇒ Object
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
|
# File 'lib/reactive_record/active_record/reactive_record/isomorphic_base.rb', line 134
def self.schedule_fetch
React::State.set_state(WhileLoading, :quiet, false)
return if @fetch_scheduled
@current_fetch_id = Time.now
@fetch_scheduled = after(0) do
next unless @pending_fetches.count > 0
saved_current_fetch_id = @current_fetch_id
saved_pending_fetches = @pending_fetches.uniq
models, associations = gather_records(@pending_records, false, nil)
log(["Server Fetching: %o", saved_pending_fetches.to_n])
start_time = `Date.now()`
Operations::Fetch.run(models: models, associations: associations, pending_fetches: saved_pending_fetches)
.then do |response|
begin
fetch_time = `Date.now()`
log(" Fetched in: #{`(fetch_time - start_time)/ 1000`}s")
timer = after(0) do
log(" Processed in: #{`(Date.now() - fetch_time) / 1000`}s")
log([' Returned: %o', response.to_n])
end
begin
ReactiveRecord::Base.load_from_json(response)
rescue Exception => e
`clearTimeout(#{timer})`
log("Unexpected exception raised while loading json from server: #{e}", :error)
end
ReactiveRecord.run_blocks_to_load saved_current_fetch_id
ensure
ReactiveRecord::WhileLoading.loaded_at saved_current_fetch_id
ReactiveRecord::WhileLoading.quiet! if @pending_fetches.empty?
end
end
.fail do |response|
log("Fetch failed", :error)
begin
ReactiveRecord.run_blocks_to_load(saved_current_fetch_id, response)
ensure
ReactiveRecord::WhileLoading.quiet! if @pending_fetches.empty?
end
end
@pending_fetches = []
@pending_records = []
@fetch_scheduled = nil
end
end
|
.serialized? ⇒ Boolean
61
62
63
|
# File 'lib/reactive_record/active_record/reactive_record/column_types.rb', line 61
def self.serialized?
@serialized_attrs ||= Hash.new { |h, k| h[k] = Hash.new }
end
|
371
372
373
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 371
def unscoped
@class_scopes[:unscoped]
end
|
.when_not_saving(model, &block) ⇒ Object
316
317
318
319
320
321
322
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 316
def self.when_not_saving(model, &block)
if @records[model].detect(&:saving?)
wait_for_save(model, &block)
else
yield model
end
end
|
Instance Method Details
#changed?(*args) ⇒ Boolean
181
182
183
184
185
186
187
188
189
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 181
def changed?(*args)
if args.count == 0
React::State.get_state(self, "!CHANGED!")
!changed_attributes.empty?
else
React::State.get_state(self, args[0])
changed_attributes.include? args[0]
end
end
|
#changed_attributes_and_values ⇒ Object
191
192
193
194
195
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 191
def changed_attributes_and_values
Hash[changed_attributes.collect do |attr|
[attr, @attributes[attr]] if column_type(attr)
end.compact]
end
|
197
198
199
200
201
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 197
def changes
Hash[changed_attributes.collect do |attr|
[attr, [@synced_attributes[attr], @attributes[attr]]] if column_type(attr)
end.compact]
end
|
#column_type(attr) ⇒ Object
12
13
14
|
# File 'lib/reactive_record/active_record/reactive_record/column_types.rb', line 12
def column_type(attr)
Base.column_type(columns_hash[attr])
end
|
#columns_hash ⇒ Object
4
5
6
|
# File 'lib/reactive_record/active_record/reactive_record/column_types.rb', line 4
def columns_hash
model.columns_hash
end
|
#convert(attr, val) ⇒ Object
65
66
67
68
69
70
71
72
73
|
# File 'lib/reactive_record/active_record/reactive_record/column_types.rb', line 65
def convert(attr, val)
column_type = column_type(attr)
return val if self.class.serialized?[model][attr] ||
!column_type || val.loading? ||
(!val && column_type != :boolean)
conversion_method = "convert_#{column_type}"
return send(conversion_method, val) if respond_to? conversion_method
val
end
|
#convert_boolean(val) ⇒ Object
39
40
41
|
# File 'lib/reactive_record/active_record/reactive_record/column_types.rb', line 39
def convert_boolean(val)
!['false', false, nil, 0].include?(val)
end
|
#convert_date(val) ⇒ Object
29
30
31
32
33
34
35
36
37
|
# File 'lib/reactive_record/active_record/reactive_record/column_types.rb', line 29
def convert_date(val)
if val.is_a?(Time)
Date.parse(val.strftime('%d/%m/%Y'))
elsif val.is_a?(Date)
val
else
Date.parse(val)
end
end
|
#convert_datetime(val) ⇒ Object
Also known as:
convert_time, convert_timestamp
16
17
18
19
20
21
22
23
24
|
# File 'lib/reactive_record/active_record/reactive_record/column_types.rb', line 16
def convert_datetime(val)
if val.is_a?(Numeric)
Time.at(val)
elsif val.is_a?(Time)
val
else
Time.parse(val)
end
end
|
#convert_float(val) ⇒ Object
Also known as:
convert_decimal
49
50
51
|
# File 'lib/reactive_record/active_record/reactive_record/column_types.rb', line 49
def convert_float(val)
Float(val)
end
|
#convert_integer(val) ⇒ Object
Also known as:
convert_bigint
43
44
45
|
# File 'lib/reactive_record/active_record/reactive_record/column_types.rb', line 43
def convert_integer(val)
Integer(`parseInt(#{val})`)
end
|
#convert_text(val) ⇒ Object
Also known as:
convert_string
55
56
57
|
# File 'lib/reactive_record/active_record/reactive_record/column_types.rb', line 55
def convert_text(val)
val.to_s
end
|
#data_loading? ⇒ Boolean
55
56
57
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 55
def data_loading?
self.class.data_loading?
end
|
#deprecation_warning(message) ⇒ Object
41
42
43
|
# File 'lib/reactive_record/active_record/reactive_record/isomorphic_base.rb', line 41
def deprecation_warning(message)
self.class.deprecation_warning(model, message)
end
|
#destroy(&block) ⇒ Object
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
|
# File 'lib/reactive_record/active_record/reactive_record/isomorphic_base.rb', line 521
def destroy(&block)
return if @destroyed
promise = Promise.new
if !data_loading? and (id or vector)
Operations::Destroy.run(model: ar_instance.model_name.to_s, id: id, vector: vector)
.then do |response|
Broadcast.to_self ar_instance
yield response[:success], response[:message] if block
promise.resolve response
end
else
destroy_associations
yield true, nil if block
promise.resolve({success: true})
end
@destroyed = true
promise
end
|
#destroy_associations ⇒ Object
404
405
406
407
408
409
410
411
412
413
414
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 404
def destroy_associations
@destroyed = false
model.reflect_on_all_associations.each do |association|
if association.collection?
@attributes[association.attribute].replace([]) if @attributes[association.attribute]
else
@ar_instance.send("#{association.attribute}=", nil)
end
end
@destroyed = true
end
|
203
204
205
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 203
def errors
@errors ||= ActiveModel::Errors.new(self)
end
|
#errors!(hash) ⇒ Object
295
296
297
298
299
300
301
302
303
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 295
def errors!(hash)
notify_waiting_for_save
errors.clear && return unless hash
hash.each do |attribute, messages|
messages.each do |message|
errors.add(attribute, message)
end
end
end
|
#find(*args) ⇒ Object
152
153
154
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 152
def find(*args)
self.class.find(*args)
end
|
#get_columns_info_for_vector(vector) ⇒ Object
120
121
122
123
124
|
# File 'lib/reactive_record/active_record/reactive_record/isomorphic_base.rb', line 120
def get_columns_info_for_vector(vector)
method_name = vector.last
method_name = method_name.first if method_name.is_a? Array
model.columns_hash[method_name] || model.server_methods[method_name]
end
|
164
165
166
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 164
def id
@attributes[primary_key]
end
|
#id=(value) ⇒ Object
168
169
170
171
172
173
174
175
176
177
178
179
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 168
def id=(value)
if !(value && (existing_record = Base.lookup_by_id(model, value)))
@attributes[primary_key] = value
Base.set_id_lookup(self)
else
@ar_instance.instance_variable_set(:@backing_record, existing_record)
existing_record.attributes.merge!(attributes) { |key, v1, v2| v1 }
end
value
end
|
#initialize_collections ⇒ Object
called when we have a newly created record, to initialize any nil collections to empty arrays. We can do this because if its a brand new record, then any collections that are still nil must not have any children.
212
213
214
215
216
217
218
219
220
221
222
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 212
def initialize_collections
if (!vector || vector.empty?) && id && id != ''
Base.set_vector_lookup(self, [@model, [:find_by, @model.primary_key => id]])
end
Base.load_data do
@model.reflect_on_all_associations.each do |assoc|
next if !assoc.collection? || @attributes[assoc.attribute]
ar_instance.send("#{assoc.attribute}=", [])
end
end
end
|
#new? ⇒ Boolean
341
342
343
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 341
def new?
!id && !vector
end
|
#new_from_vector(*args) ⇒ Object
156
157
158
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 156
def new_from_vector(*args)
self.class.new_from_vector(*args)
end
|
#notify_waiting_for_save ⇒ Object
324
325
326
327
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 324
def notify_waiting_for_save
@saving = false
self.class.notify_waiting_for_save(model)
end
|
#primary_key ⇒ Object
160
161
162
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 160
def primary_key
@model.primary_key
end
|
45
46
47
|
# File 'lib/reactive_record/active_record/reactive_record/isomorphic_base.rb', line 45
def records
self.class.instance_variable_get(:@records)
end
|
281
282
283
284
285
286
287
288
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 281
def revert
@changed_attributes.dup.each do |attribute|
@ar_instance.send("#{attribute}=", @synced_attributes[attribute])
@attributes.delete(attribute) unless @synced_attributes.key?(attribute)
end
@changed_attributes = []
errors.clear
end
|
#save_or_validate(save, validate, force, &block) ⇒ Object
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
|
# File 'lib/reactive_record/active_record/reactive_record/isomorphic_base.rb', line 248
def save_or_validate(save, validate, force, &block)
if data_loading?
sync!
elsif force || changed? || (validate && new?)
HyperMesh.load do
ReactiveRecord.loads_pending! unless self.class.pending_fetches.empty?
end.then { send_save_to_server(save, validate, force, &block) }
else
promise = Promise.new
yield true, nil, [] if block
promise.resolve({success: true})
promise
end
end
|
#saved!(save_only = nil) ⇒ Object
sets saving to false AND notifies
305
306
307
308
309
310
311
312
313
314
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 305
def saved!(save_only = nil)
notify_waiting_for_save
return self if save_only
if errors.empty?
React::State.set_state(self, self, :saved)
elsif !data_loading?
React::State.set_state(self, self, :error)
end
self
end
|
290
291
292
293
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 290
def saving!
React::State.set_state(self, self, :saving) unless data_loading?
@saving = true
end
|
#saving? ⇒ Boolean
336
337
338
339
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 336
def saving?
React::State.get_state(self, self)
@saving
end
|
#send_save_to_server(save, validate, force, &block) ⇒ Object
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
|
# File 'lib/reactive_record/active_record/reactive_record/isomorphic_base.rb', line 264
def send_save_to_server(save, validate, force, &block)
models, associations, backing_records = self.class.gather_records([self], force, self)
begin
backing_records.each { |id, record| record.saving! } if save
promise = Promise.new
Operations::Save.run(models: models, associations: associations, save: save, validate: validate)
.then do |response|
begin
response[:models] = response[:saved_models].collect do |item|
backing_records[item[0]].ar_instance
end
if save
if response[:success]
response[:saved_models].each do |item|
Broadcast.to_self backing_records[item[0]].ar_instance, item[2]
end
else
log(response[:message], :error)
response[:saved_models].each do |item|
log(" Model: #{item[1]}[#{item[0]}] Attributes: #{item[2]} Errors: #{item[3]}", :error) if item[3]
end
end
end
response[:saved_models].each do | item |
backing_records[item[0]].sync_unscoped_collection! if save
backing_records[item[0]].errors! item[3]
end
yield response[:success], response[:message], response[:models] if block
promise.resolve response
rescue Exception => e
log("Exception raised while saving - #{e}", :error)
ensure
backing_records.each { |_id, record| record.saved! rescue nil } if save
end
end
promise
rescue Exception => e
backing_records.each { |_id, record| record.saved!(true) rescue nil } if save
end
rescue Exception => e
debugger
log("Exception raised while saving - #{e}", :error)
yield false, e.message, [] if block
promise.resolve({success: false, message: e.message, models: []})
promise
end
|
#set_ar_instance! ⇒ Object
345
346
347
348
349
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 345
def set_ar_instance!
klass = self.class.infer_type_from_hash(model, @attributes)
@ar_instance = klass._new_without_sti_type_cast(self) unless @ar_instance.class == klass
@ar_instance
end
|
#sync!(hash = {}) ⇒ Object
sync! now will also initialize any nil collections
225
226
227
228
229
230
231
232
233
234
235
236
237
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 225
def sync!(hash = {})
@synced_attributes = {}
hash.each { |attr, value| sync_attribute(attr, convert(attr, value)) }
@changed_attributes = []
@saving = false
errors.clear
initialize_collections if (!vector || vector.empty?) && id && id != ''
self
end
|
#sync_attribute(attribute, value) ⇒ Object
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 254
def sync_attribute(attribute, value)
@synced_attributes[attribute] = @attributes[attribute] = value
Base.set_id_lookup(self) if attribute == primary_key
if value.is_a? Collection
@synced_attributes[attribute] = value.dup_for_sync
elsif aggregation = model.reflect_on_aggregation(attribute) and (aggregation.klass < ActiveRecord::Base)
value.backing_record.sync!
elsif aggregation
@synced_attributes[attribute] = aggregation.deserialize(aggregation.serialize(value))
elsif !model.reflect_on_association(attribute)
@synced_attributes[attribute] = JSON.parse(value.to_json)
end
@changed_attributes.delete(attribute)
value
end
|
#sync_unscoped_collection! ⇒ Object
this keeps the unscoped collection up to date. to collections that just have a count
242
243
244
245
246
247
248
249
250
251
252
|
# File 'lib/reactive_record/active_record/reactive_record/base.rb', line 242
def sync_unscoped_collection!
if destroyed
return if @destroy_sync
@destroy_sync = true
else
return if @create_sync
@create_sync = true
end
model.unscoped << ar_instance
@synced_with_unscoped = !@synced_with_unscoped
end
|