Class: KlaviyoAPI::ListMember

Inherits:
Base
  • Object
show all
Defined in:
lib/klaviyo_api/resources/list_member.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

activate_session, element_path, headers, reset_session, #to_h

Class Method Details

.bulk_create(list_members, options = {}) ⇒ Object

A shortcut to create multiple ListMembers at once, as supported by the Klaviyo API.

www.klaviyo.com/docs/api/v2/lists#post-members



27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/klaviyo_api/resources/list_member.rb', line 27

def bulk_create(list_members, options = {})
  payload = { profiles: list_members }.to_json

  saved_list_members = []
  connection.post(collection_path(options), payload, headers).tap do |response|
    list_members_json = JSON.parse(response.body)
    list_members_json.each do |list_member_json|
      saved_list_members << KlaviyoAPI::ListMember.new(list_member_json)
    end
  end
  saved_list_members
end

.delete(email, options = {}) ⇒ Object

Removing a Member from a List is a DELETE call, but no ID is given. Instead, the email must be provided in the query params. Klaviyo also accepts an array in the body, but Ruby’s HTTP library does not support DELETE bodies (as per the HTTP spec).

www.klaviyo.com/docs/api/v2/lists#delete-members



18
19
20
21
# File 'lib/klaviyo_api/resources/list_member.rb', line 18

def delete(email, options = {})
  options = options.merge({emails: email})
  connection.delete(element_path('', options), headers)
end

Instance Method Details

#createObject

Adding a single Member to a List does not exist - they must be added as an array of Profiles. In order to fit AR, we need to wrap self in an array, and remove it in the response.

www.klaviyo.com/docs/api/v2/lists#post-members



46
47
48
49
50
51
52
53
54
55
56
# File 'lib/klaviyo_api/resources/list_member.rb', line 46

def create
  payload = { profiles: [self] }.to_json

  run_callbacks :create do
    connection.post(collection_path, payload, self.class.headers).tap do |response|
      response.body = JSON.parse(response.body)[0].to_json
      self.id = id_from_response(response)
      load_attributes_from_response(response)
    end
  end
end

#destroyObject

Can only delete by email, not ID.

www.klaviyo.com/docs/api/v2/lists#delete-members



61
62
63
64
65
# File 'lib/klaviyo_api/resources/list_member.rb', line 61

def destroy
  run_callbacks :destroy do
    KlaviyoAPI::ListMember.delete self.email, prefix_options
  end
end

#updateObject



67
68
69
# File 'lib/klaviyo_api/resources/list_member.rb', line 67

def update
  raise KlaviyoAPI::InvalidOperation.new 'Cannot update list members. You might be looking for delete and/or create.'
end