Method: NotionAPI::CollectionView#create_singleton_methods_and_instance_variables

Defined in:
lib/notion_api/notion_types/collection_view_blocks.rb

#create_singleton_methods_and_instance_variables(row, row_data) ⇒ Object



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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
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
# File 'lib/notion_api/notion_types/collection_view_blocks.rb', line 214

def create_singleton_methods_and_instance_variables(row, row_data)
  # ! creates singleton methods for each property in a CollectionView.
  # ! row -> the block ID of the 'row' to retrieve: ``str``
  # ! row_data -> the data corresponding to that row, should be key-value pairs where the keys are the columns: ``hash``
  collection_data = extract_collection_data(@collection_id, @view_id)
  schema = collection_data["collection"][collection_id]["value"]["schema"]
  column_mappings = schema.keys
  column_hash = {}
  column_names = column_mappings.map { |mapping| column_hash[mapping] = schema[mapping]["name"].downcase }

  column_hash.keys.each_with_index do |column, i|
    # loop over the column names...
    # set instance variables for each column, allowing the dev to 'read' the column value
    cleaned_column = clean_property_names(column_hash, column)

    if row_data["value"]["properties"].nil? or row_data["value"]["properties"][column].nil?
      value = ""
    else
      value = row_data["value"]["properties"][column][0][0]
      if [""].include?(value.to_s)
        value = row_data["value"]["properties"][column][0][1].flatten[-1]
      end
    end

    row.instance_variable_set("@#{cleaned_column}", value)
    CollectionViewRow.class_eval { attr_reader cleaned_column }
    # then, define singleton methods for each column that are used to update the table cell
    row.define_singleton_method("#{cleaned_column}=") do |new_value|
      # neat way to get the name of the currently invoked method...
      parsed_method = __method__.to_s[0...-1].split("_").join(" ")
      cookies = Core.options["cookies"]
      headers = Core.options["headers"]

      request_id = extract_id(SecureRandom.hex(16))
      transaction_id = extract_id(SecureRandom.hex(16))
      space_id = extract_id(SecureRandom.hex(16))

      request_ids = {
        request_id: request_id,
        transaction_id: transaction_id,
        space_id: space_id,
      }

      update_property_value_hash = Utils::CollectionViewComponents.update_property_value(@id, column_hash.key(parsed_method), new_value, schema[column_hash.key(parsed_method)]["type"])

      operations = [
        update_property_value_hash,
      ]

      if %q[select multi_select].include?(schema[column_hash.key(parsed_method)]["type"])
        options = schema[column_hash.key(parsed_method)]["options"].nil? ? [] : schema[column_hash.key(parsed_method)]["options"].map { |option| option["value"] }
        multi_select_multi_options = new_value.split(",")
        multi_select_multi_options.each do |option|
          if !options.include?(option.strip)
            create_new_option = Utils::CollectionViewComponents.add_new_option(column_hash.key(parsed_method), option.strip, @collection_id)
            operations.push(create_new_option)
          end
        end
      end

      request_url = URLS[:UPDATE_BLOCK]
      request_body = build_payload(operations, request_ids)
      response = HTTParty.post(
        request_url,
        body: request_body.to_json,
        cookies: cookies,
        headers: headers,
      )
      unless response.code == 200; raise "There was an issue completing your request. Here is the response from Notion: #{response.body}, and here is the payload that was sent: #{operations}.
           Please try again, and if issues persist open an issue in GitHub.";           end

      # set the instance variable to the updated value!
      _ = row.instance_variable_set("@#{__method__.to_s[0...-1]}", new_value)
      row
    end
  end
end