Created
February 25, 2016 18:48
-
-
Save maccman/f88483f3cc9f338a4550 to your computer and use it in GitHub Desktop.
Clearbit & Customer.io integration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UserSignup | |
# We're using a job queuing service called Sidekiq | |
# so that signups are processed and pushed to | |
# customer.io asyncronously. | |
include Sidekiq::Worker | |
attr_reader :user, :lookup | |
def perform(user_id) | |
# Find the user by ID | |
@user = User[user_id] | |
# Perform the Clearbit lookup | |
@lookup = lookup_email | |
# Send the data to customer.io | |
notify_customerio | |
end | |
protected | |
def notify_customer_io | |
# Put together basic attributes | |
# for customer.io (id is required) | |
attrs = { | |
id: user.id, | |
email: user.email, | |
given_name: user.given_name, | |
family_name: user.family_name | |
} | |
# Merge in prefixed and flattened Clearbit data | |
attrs.merge!(person_data) | |
attrs.merge!(company_data) | |
# Send everything to customer.io | |
customerio_client.identify(attrs) | |
end | |
def lookup_email | |
result = suppress Nestful::ConnectionError, ArgumentError do | |
Clearbit::Enrichment.find( | |
email: user.email, | |
given_name: user.given_name, | |
family_name: user.family_name, | |
stream: true | |
) | |
end | |
result || Mash.new | |
end | |
def customerio_client | |
Customerio::Client.new( | |
ENV['CUSTOMERIO_KEY'], | |
ENV['CUSTOMERIO_SECRET'], | |
json: true | |
) | |
end | |
def person_data | |
return {} unless lookup.person | |
data = lookup.person | |
data = flat_hash(data) | |
data = prefix(data, 'person') | |
data | |
end | |
def company_data | |
return {} unless lookup.company | |
data = lookup.company | |
data = flat_hash(data) | |
data = prefix(data, 'company') | |
data | |
end | |
def prefix(hash, prefix_key) | |
hash.inject({}) do |result, (key, value)| | |
result.merge!("#{prefix_key}_#{key}" => value) | |
end | |
end | |
def flat_hash(hash) | |
flat_hash_array(hash).inject({}) do |hash, (key, value)| | |
hash.merge!(Array(key).join('_').underscore => value) | |
end | |
end | |
def flat_hash_array(hash, keys=[], result={}) | |
return result.update(keys => hash) unless hash.is_a?(Hash) | |
hash.each {|k,r| flat_hash_array(r, keys+[k], result) } | |
result | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment