Created
June 30, 2010 18:28
-
-
Save ntalbott/459047 to your computer and use it in GitHub Desktop.
An example script that counts the active subscribers in a Spreedly site using the transaction history.
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
SITE = ARGV[0] | |
TOKEN = ARGV[1] | |
require 'rubygems' | |
require 'nokogiri' | |
def next_transactions(since=0) | |
puts "Requesting transactions since #{since}" | |
doc = Nokogiri::XML(`curl -s -S -u #{TOKEN}:X https://spreedly.com/api/v4/#{SITE}/transactions.xml?since_id=#{since}`) | |
(doc/'transaction').collect do |t| | |
{:id => (t/'id').first.content, | |
:type => (t/'detail-type').first.content, | |
:customer_id => (t/'subscriber-customer-id').first.content, | |
:succeeded => (t/'succeeded').first.content} | |
end | |
end | |
def process(transaction, subscribers) | |
return unless transaction[:succeeded] == 'true' | |
subscriber = subscribers[transaction[:customer_id]] | |
case transaction[:type] | |
when 'Subscription', 'ComplimentarySubscription', 'LifetimeComplimentarySubscription', 'Renewal' | |
subscriber[:active] = true | |
when 'Expiration', 'Cancellation' | |
subscriber[:active] = false | |
end | |
end | |
last = 0 | |
subscribers = Hash.new{|h,k| h[k] = {}} | |
loop do | |
transactions = next_transactions(last) | |
break if transactions.empty? | |
transactions.each do |transaction| | |
process(transaction, subscribers) | |
end | |
last = transactions.last[:id] | |
end | |
currently_active = subscribers.values.select{|subscriber| subscriber[:active]}.size | |
puts "Currently active subscribers: #{currently_active}" |
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
ntalbott@joshua:~/git/spreedly/tmp$ ruby active_subscriber_counter.rb [site] [token] | |
Requesting transactions since 0 | |
Requesting transactions since 231501 | |
Requesting transactions since 240493 | |
Currently active subscribers: 64 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment