Class: Norairrecord::Table

Inherits:
Object
  • Object
show all
Extended by:
Util
Defined in:
lib/norairrecord/table.rb

Constant Summary collapse

BATCH_SIZE =
10

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Util

all_of, any_of, field_is_any, mass_sanitize, none_of, sanitize

Constructor Details

#initialize(fields, id: nil, created_at: nil) ⇒ Table

Returns a new instance of Table.



285
286
287
288
289
# File 'lib/norairrecord/table.rb', line 285

def initialize(*one, **two)
  @id = one.first && two.delete(:id)
  self.created_at = one.first && two.delete(:created_at)
  self.fields = one.first || two
end

Class Attribute Details

.api_keyObject



35
36
37
# File 'lib/norairrecord/table.rb', line 35

def api_key
  defined?(@api_key) ? @api_key : Norairrecord.api_key
end

.base_keyObject



12
13
14
# File 'lib/norairrecord/table.rb', line 12

def base_key
  @base_key || (superclass < Table ? superclass.base_key : nil)
end

.table_nameObject



16
17
18
# File 'lib/norairrecord/table.rb', line 16

def table_name
  @table_name || (superclass < Table ? superclass.table_name : nil)
end

Instance Attribute Details

#created_atObject

Returns the value of attribute created_at.



280
281
282
# File 'lib/norairrecord/table.rb', line 280

def created_at
  @created_at
end

#fieldsObject

Returns the value of attribute fields.



280
281
282
# File 'lib/norairrecord/table.rb', line 280

def fields
  @fields
end

#idObject (readonly)

Returns the value of attribute id.



280
281
282
# File 'lib/norairrecord/table.rb', line 280

def id
  @id
end

#updated_keysObject (readonly)

Returns the value of attribute updated_keys.



280
281
282
# File 'lib/norairrecord/table.rb', line 280

def updated_keys
  @updated_keys
end

Class Method Details

._create(fields, options = {}) ⇒ Object



107
108
109
# File 'lib/norairrecord/table.rb', line 107

def _create(fields, options = {})
  _new(fields).tap { |record| record._save(options) }
end

._new(*args, **kwargs) ⇒ Object



103
104
105
# File 'lib/norairrecord/table.rb', line 103

def _new(*args, **kwargs)
  new(*args, **kwargs)
end

._update(id, update_hash = {}, options = {}) ⇒ Object Also known as: update



86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/norairrecord/table.rb', line 86

def _update(id, update_hash = {}, options = {})
  # To avoid trying to update computed fields we *always* use PATCH
  body = {
    fields: update_hash,
    **options
  }.to_json

  response = client.connection.patch("v0/#{base_key}/#{client.escape(table_name)}/#{id}", body, { 'Content-Type' => 'application/json' })
  parsed_response = client.parse(response.body)

  if response.success?
    parsed_response["fields"]
  else
    client.handle_error(response.status, parsed_response)
  end
end

.batch_create(recs, options = {}) ⇒ Object



245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
# File 'lib/norairrecord/table.rb', line 245

def batch_create(recs, options = {})
  records = []
  recs.each_slice(BATCH_SIZE) do |chunk|
    body = {
      records: chunk.map { |record| { fields: record.serializable_fields } },
      **options
    }.to_json

    response = client.connection.post("v0/#{base_key}/#{client.escape(table_name)}", body, { 'Content-Type' => 'application/json' })
    parsed_response = client.parse(response.body)

    if response.success?
      records.concat(parsed_response["records"])
    else
      client.handle_error(response.status, parsed_response)
    end
  end
  map_new records
end

.batch_save(records) ⇒ Object



270
271
272
273
274
275
# File 'lib/norairrecord/table.rb', line 270

def batch_save(records)
  res = []
  to_be_created, to_be_updated = records.partition &:new_record?
  res.concat(batch_create(to_be_created))
  res.concat(batch_update(to_be_updated))
end

.batch_update(recs, options = {}) ⇒ Object



186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
# File 'lib/norairrecord/table.rb', line 186

def batch_update(recs, options = {})
  res = []
  recs.each_slice(BATCH_SIZE) do |chunk|
    body = {
      records: chunk.map do |record|
        {
          fields: record.update_hash,
          id: record.id,
        }
      end,
      **options
    }.to_json

    response = client.connection.patch("v0/#{base_key}/#{client.escape(table_name)}", body, { 'Content-Type' => 'application/json' })
    parsed_response = client.parse(response.body)
    if response.success?
      res.concat(parsed_response["records"])
    else
      client.handle_error(response.status, parsed_response)
    end
  end
  map_new res
end

.batch_upsert(recs, merge_fields, options = {}, include_ids: nil, hydrate: false) ⇒ Object



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
# File 'lib/norairrecord/table.rb', line 210

def batch_upsert(recs, merge_fields, options = {}, include_ids: nil, hydrate: false)
  merge_fields = Array(merge_fields) # allows passing in a single field

  created, updated, records = [], [], []

  recs.each_slice(BATCH_SIZE) do |chunk|
    body = {
      records: chunk.map { |rec| { fields: rec.fields, id: (include_ids ? rec.id : nil) }.compact },
      **options,
      performUpsert: { fieldsToMergeOn: merge_fields }
    }.to_json

    response = client.connection.patch("v0/#{base_key}/#{client.escape(table_name)}", body, { 'Content-Type' => 'application/json' })
    parsed_response = response.success? ? client.parse(response.body) : client.handle_error(response.status, client.parse(response.body))

    if response.success?
      created.concat(parsed_response.fetch('createdRecords', []))
      updated.concat(parsed_response.fetch('updatedRecords', []))
      records.concat(parsed_response.fetch('records', []))
    else
      client.handle_error(response.status, parsed_response)
    end
  end

  if hydrate && records.any?
    record_hash = records.map { |record| [record["id"], self.new_with_subtype(record["fields"], id: record["id"], created_at: record["createdTime"])] }.to_h

    created.map! { |id| record_hash[id] }.compact!
    updated.map! { |id| record_hash[id] }.compact!
    records = record_hash.values
  end

  { created:, updated:, records: }
end

.belongs_to(method_name, options) ⇒ Object Also known as: has_one



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

def belongs_to(method_name, options)
  has_many(method_name, options.merge(single: true))
end

.clientObject



30
31
32
33
# File 'lib/norairrecord/table.rb', line 30

def client
  @@clients ||= {}
  @@clients[api_key] ||= Client.new(api_key)
end

.createObject



112
113
114
# File 'lib/norairrecord/table.rb', line 112

def _create(fields, options = {})
  _new(fields).tap { |record| record._save(options) }
end

.find(id) ⇒ Object



67
68
69
70
71
72
73
74
75
76
# File 'lib/norairrecord/table.rb', line 67

def find(id)
  response = client.connection.get("v0/#{base_key}/#{client.escape(table_name)}/#{id}")
  parsed_response = client.parse(response.body)

  if response.success?
    self.new_with_subtype(parsed_response["fields"], id: id, created_at: parsed_response["createdTime"])
  else
    client.handle_error(response.status, parsed_response)
  end
end

.find_many(ids, where: nil, sort: nil) ⇒ Object



78
79
80
81
82
83
84
# File 'lib/norairrecord/table.rb', line 78

def find_many(ids, where: nil, sort: nil)
  return [] if ids.empty?

  formula = any_of(ids.map { |id| "RECORD_ID() = '#{id}'" })
  formula = all_of(formula, where) if where
  records(filter: formula, sort:).sort_by { |record| or_args.index(record.id) }
end

.first(options = {}) ⇒ Object



168
169
170
# File 'lib/norairrecord/table.rb', line 168

def first(options = {})
  records(**options.merge(max_records: 1)).first
end

.first_where(filter, options = {}) ⇒ Object



172
173
174
# File 'lib/norairrecord/table.rb', line 172

def first_where(filter, options = {})
  first(options.merge(filter:))
end

.has_many(method_name, options) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/norairrecord/table.rb', line 39

def has_many(method_name, options)
  define_method(method_name.to_sym) do |where: nil, sort: nil|
    # Get association ids in reverse order, because Airtable's UI and API
    # sort associations in opposite directions. We want to match the UI.
    ids = (self[options.fetch(:column)] || []).reverse
    table = Kernel.const_get(options.fetch(:class))
    return table.find_many(ids, sort:, where:) unless options[:single]

    (id = ids.first) ? table.find(id) : nil
  end

  define_method("#{method_name}=".to_sym) do |value|
    __set_field(options.fetch(:column), Array(value).map(&:id).reverse)
  end
end

.has_subtypes(column, mapping, strict: false) ⇒ Object



61
62
63
64
65
# File 'lib/norairrecord/table.rb', line 61

def has_subtypes(column, mapping, strict: false)
  @subtype_column = column
  @subtype_mapping = mapping
  @subtype_strict = strict
end

.map_new(arr) ⇒ Object



180
181
182
183
184
# File 'lib/norairrecord/table.rb', line 180

def map_new(arr)
  arr.map do |record|
    self.new_with_subtype(record["fields"], id: record["id"], created_at: record["createdTime"])
  end
end

.new_with_subtype(fields, id:, created_at:) ⇒ Object



114
115
116
117
118
119
120
121
122
123
124
# File 'lib/norairrecord/table.rb', line 114

def new_with_subtype(fields, id:, created_at:)
  if @subtype_column
    clazz = self
    st = @subtype_mapping[fields[@subtype_column]]
    raise Norairrecord::UnknownTypeError, "#{fields[@subtype_column]}?????" if @subtype_strict && st.nil?
    clazz = Kernel.const_get(st) if st
    clazz._new(fields, id:, created_at:)
  else
    self._new(fields, id: id, created_at: created_at)
  end
end

.records(filter: nil, sort: nil, view: nil, offset: nil, paginate: true, fields: nil, max_records: nil, page_size: nil) ⇒ Object Also known as: all



126
127
128
129
130
131
132
133
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
# File 'lib/norairrecord/table.rb', line 126

def records(filter: nil, sort: nil, view: nil, offset: nil, paginate: true, fields: nil, max_records: nil, page_size: nil)
  options = {}
  options[:filterByFormula] = filter if filter

  if sort
    options[:sort] = sort.map { |field, direction|
      { field: field.to_s, direction: direction }
    }
  end

  options[:view] = view if view
  options[:offset] = offset if offset
  options[:fields] = fields if fields
  options[:maxRecords] = max_records if max_records
  options[:pageSize] = page_size if page_size

  path = "v0/#{base_key}/#{client.escape(table_name)}/listRecords"
  response = client.connection.post(path, options.to_json, { 'Content-Type' => 'application/json' })
  parsed_response = client.parse(response.body)

  if response.success?
    records = map_new parsed_response["records"]

    if paginate && parsed_response["offset"]
      records.concat(records(
                       filter: filter,
                       sort: sort,
                       view: view,
                       paginate: paginate,
                       fields: fields,
                       offset: parsed_response["offset"],
                       max_records: max_records,
                       page_size: page_size,
                     ))
    end

    records
  else
    client.handle_error(response.status, parsed_response)
  end
end

.responsible_classObject

finds the actual parent class of a (possibly) subtype class



22
23
24
25
26
27
28
# File 'lib/norairrecord/table.rb', line 22

def responsible_class
  if @base_key
    self.class
  else
    superclass < Table ? superclass.responsible_class : nil
  end
end

.upsert(fields, merge_fields, options = {}) ⇒ Object



265
266
267
268
# File 'lib/norairrecord/table.rb', line 265

def upsert(fields, merge_fields, options = {})
  record = batch_upsert([self._new(fields)], merge_fields, options)&.dig(:records, 0)
  record ? _new(record) : nil
end

.where(filter, options = {}) ⇒ Object



176
177
178
# File 'lib/norairrecord/table.rb', line 176

def where(filter, options = {})
  records(**options.merge(filter:))
end

Instance Method Details

#==(other) ⇒ Object Also known as: eql?



390
391
392
393
# File 'lib/norairrecord/table.rb', line 390

def ==(other)
  self.class == other.class &&
    serializable_fields == other.serializable_fields
end

#[](key) ⇒ Object



302
303
304
305
# File 'lib/norairrecord/table.rb', line 302

def [](key)
  validate_key(key)
  fields[key]
end

#__set_field(key, value) ⇒ Object Also known as: []=



307
308
309
310
311
312
313
# File 'lib/norairrecord/table.rb', line 307

def __set_field(key, value)
  validate_key(key)
  return if fields[key] == value # no-op

  @updated_keys << key
  fields[key] = value
end

#_create(options = {}) ⇒ Object Also known as: create

Raises:



323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
# File 'lib/norairrecord/table.rb', line 323

def _create(options = {})
  raise Error, "Record already exists (record has an id)" unless new_record?

  body = {
    fields: serializable_fields,
    **options
  }.to_json

  response = client.connection.post("v0/#{self.class.base_key}/#{client.escape(self.class.table_name)}", body, { 'Content-Type' => 'application/json' })
  parsed_response = client.parse(response.body)

  if response.success?
    @id = parsed_response["id"]
    self.created_at = parsed_response["createdTime"]
    self.fields = parsed_response["fields"]
  else
    client.handle_error(response.status, parsed_response)
  end
end

#_save(options = {}) ⇒ Object Also known as: save



343
344
345
346
347
# File 'lib/norairrecord/table.rb', line 343

def _save(options = {})
  return _create(options) if new_record?
  return true if @updated_keys.empty?
  self.fields = self.class._update(self.id, self.update_hash, options)
end

#airtable_urlObject



386
387
388
# File 'lib/norairrecord/table.rb', line 386

def airtable_url
  "https://airtable.com/#{self.class.base_key}/#{self.class.table_name}/#{self.id}"
end

#comment(text) ⇒ Object



375
376
377
378
379
380
381
382
383
384
# File 'lib/norairrecord/table.rb', line 375

def comment(text)
  response = client.connection.post("v0/#{self.class.base_key}/#{client.escape(self.class.table_name)}/#{self.id}/comments", { text: }.to_json, { 'Content-Type' => 'application/json' })
  parsed_response = client.parse(response.body)

  if response.success?
    parsed_response['id']
  else
    client.handle_error(response.status, parsed_response)
  end
end

#destroyObject

Raises:



358
359
360
361
362
363
364
365
366
367
368
369
# File 'lib/norairrecord/table.rb', line 358

def destroy
  raise Error, "Unable to destroy new record" if new_record?

  response = client.connection.delete("v0/#{self.class.base_key}/#{client.escape(self.class.table_name)}/#{self.id}")
  parsed_response = client.parse(response.body)

  if response.success?
    true
  else
    client.handle_error(response.status, parsed_response)
  end
end

#hashObject



397
398
399
# File 'lib/norairrecord/table.rb', line 397

def hash
  serializable_fields.hash
end

#new_record?Boolean

Returns:

  • (Boolean)


298
299
300
# File 'lib/norairrecord/table.rb', line 298

def new_record?
  !id
end

#patch(updates = {}, options = {}) ⇒ Object



317
318
319
320
321
# File 'lib/norairrecord/table.rb', line 317

def patch(updates = {}, options = {})
  updates.reject! { |key, value| @fields[key] == value }
  return @fields if updates.empty? # don't hit AT if we don't have real changes
  @fields.merge!(self.class._update(self.id, updates, options).reject { |key, _| updated_keys.include?(key) })
end

#serializable_fieldsObject



371
372
373
# File 'lib/norairrecord/table.rb', line 371

def serializable_fields
  fields
end

#transaction(&block) ⇒ Object

ahahahahaha



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
# File 'lib/norairrecord/table.rb', line 402

def transaction(&block)
  txn_updates = {}

  singleton_class.define_method(:original_setter, method(:__set_field))

  define_singleton_method(:__set_field) do |key, value|
    txn_updates[key] = value
  end

  singleton_class.send(:alias_method, :[]=, :__set_field)

  begin
    result = yield self
    @updated_keys -= txn_updates.keys
    if new_record?
      @fields.merge!(txn_updates)
      _save
    else
      self.patch(txn_updates)
    end
  rescue => e
    raise
  ensure
    singleton_class.define_method(:[]=, method(:original_setter))
    singleton_class.remove_method(:original_setter)
  end
  result
end

#update_hashObject



352
353
354
355
356
# File 'lib/norairrecord/table.rb', line 352

def update_hash
  Hash[@updated_keys.map { |key|
    [key, fields[key]]
  }]
end