Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

Allow objects to store their details #16

Closed
wants to merge 10 commits into from

3 participants

@martingordon

It's a pain to have to keep around both a list/client/segment object and a corresponding hash of details. These changes allow storing of the details as attributes on the object in standard Ruby notation (underscored instead of camel cased).

The changes are backwards-compatible. The details methods will still return the response hash.

@jdennes
Collaborator

I'm sorry this work was never merged into master. I was away and not actively maintaining this project when this pull request was made, and unfortunately nobody else looked at this.

The library has changed significantly since then, and this can't really be merged as it stands right now. I may end up using the ideas from this pull request to implement what you have done using the latest code.

@jdennes jdennes closed this
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
This page is out of date. Refresh to see the latest.
View
8 Gemfile.lock
@@ -3,7 +3,7 @@ PATH
specs:
createsend (1.0.3)
hashie (~> 1.0)
- httparty (~> 0.8)
+ httparty
json
GEM
@@ -15,12 +15,12 @@ GEM
multi_json
multi_xml
jnunemaker-matchy (0.4.0)
- json (1.6.1)
+ json (1.6.6)
metaclass (0.0.1)
mocha (0.10.0)
metaclass (~> 0.0.1)
- multi_json (1.0.3)
- multi_xml (0.4.1)
+ multi_json (1.3.2)
+ multi_xml (0.4.2)
rake (0.9.2.2)
shoulda (3.0.1)
shoulda-context (~> 1.0.0)
View
14 README.md
@@ -15,9 +15,9 @@ Retrieve a list of all your clients.
require 'createsend'
- CreateSend.api_key 'your_api_key'
-
- cs = CreateSend::CreateSend.new
+ api_key = 'your_api_key'
+
+ cs = CreateSend::CreateSend.new(api_key)
clients = cs.clients
clients.each do |c|
@@ -34,11 +34,11 @@ If the createsend API returns an error, an exception will be thrown. For example
require 'createsend'
- CreateSend.api_key 'your_api_key'
+ api_key = 'your_api_key'
begin
- cl = CreateSend::Client.new "4a397ccaaa55eb4e6aa1221e1e2d7122"
- id = CreateSend::Campaign.create cl.client_id, "", "", "", "", "", "", "", [], []
+ cl = CreateSend::Client.new "4a397ccaaa55eb4e6aa1221e1e2d7122", api_key
+ id = CreateSend::Campaign.create cl.client_id, "", "", "", "", "", "", "", [], [], api_key
puts "New campaign ID: #{id}"
rescue CreateSend::BadRequest => br
puts "Bad request error: #{br}"
@@ -62,6 +62,6 @@ For example, if you wanted to find out how to call the CreateSend::Subscriber.ad
should "add a subscriber with custom fields" do
stub_post(@api_key, "subscribers/#{@list_id}.json", "add_subscriber.json")
custom_fields = [ { :Key => 'website', :Value => 'http://example.com/' } ]
- email_address = CreateSend::Subscriber.add @list_id, "subscriber@example.com", "Subscriber", custom_fields, true
+ email_address = CreateSend::Subscriber.add @list_id, "subscriber@example.com", "Subscriber", custom_fields, true, api_key
email_address.should == "subscriber@example.com"
end
View
2  createsend.gemspec
@@ -11,7 +11,7 @@ Gem::Specification.new do |s|
s.add_development_dependency('shoulda', '~> 3.0.1')
s.add_runtime_dependency('json')
s.add_runtime_dependency('hashie', '~> 1.0')
- s.add_runtime_dependency('httparty', '~> 0.8')
+ s.add_runtime_dependency('httparty')
s.name = "createsend"
s.author = "James Dennes"
s.description = %q{Implements the complete functionality of the createsend API.}
View
14 lib/core_ext/string.rb
@@ -0,0 +1,14 @@
+class String
+ # Taken from ActiveSupport
+ # File activesupport/lib/active_support/inflector.rb, line 188
+
+ unless self.new.respond_to? :underscore
+ def underscore
+ gsub(/::/, '/').
+ gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
+ gsub(/([a-z\d])([A-Z])/,'\1_\2').
+ tr("-", "_").
+ downcase
+ end
+ end
+end
View
62 lib/createsend.rb
@@ -14,14 +14,16 @@
require 'createsend/subscriber'
require 'createsend/template'
+require 'core_ext/string'
+
module CreateSend
# Just allows callers to do CreateSend.api_key "..." rather than CreateSend::CreateSend.api_key "..." etc
class << self
- def api_key(api_key=nil)
- r = CreateSend.api_key api_key
+ def new(api_key)
+ CreateSend.new api_key
end
-
+
def base_uri(uri)
r = CreateSend.base_uri uri
end
@@ -48,7 +50,7 @@ class Unavailable < StandardError; end
# Provides high level CreateSend functionality/data you'll probably need.
class CreateSend
include HTTParty
-
+
class Parser::DealWithCreateSendInvalidJson < HTTParty::Parser
# The createsend API returns an ID as a string when a 201 Created
# response is returned. Unfortunately this is invalid json.
@@ -62,55 +64,75 @@ def parse
end
parser Parser::DealWithCreateSendInvalidJson
@@base_uri = "https://api.createsend.com/api/v3"
- @@api_key = ""
- headers({
- 'User-Agent' => "createsend-ruby-#{VERSION}",
+ # @api_key = ""
+ headers({
+ 'User-Agent' => "createsend-ruby-#{VERSION}",
'Content-Type' => 'application/json; charset=utf-8',
'Accept-Encoding' => 'gzip, deflate' })
base_uri @@base_uri
- basic_auth @@api_key, 'x'
- # Sets the API key which will be used to make calls to the CreateSend API.
- def self.api_key(api_key=nil)
- return @@api_key unless api_key
- @@api_key = api_key
- basic_auth @@api_key, 'x'
+ def initialize(api_key)
+ @api_key = api_key
end
# Gets your CreateSend API key, given your site url, username and password.
- def apikey(site_url, username, password)
+ def apikey(site_url, username, password)
site_url = CGI.escape(site_url)
self.class.basic_auth username, password
response = CreateSend.get("/apikey.json?SiteUrl=#{site_url}")
# Revert basic_auth to use @@api_key, 'x'
- self.class.basic_auth @@api_key, 'x'
+ self.class.basic_auth @api_key, 'x'
Hashie::Mash.new(response)
end
# Gets your clients.
def clients
- response = CreateSend.get('/clients.json')
+ response = self.get('/clients.json')
response.map{|item| Hashie::Mash.new(item)}
end
# Gets valid countries.
def countries
- response = CreateSend.get('/countries.json')
+ response = self.get('/countries.json')
response.parsed_response
end
# Gets the current date in your account's timezone.
def systemdate
- response = CreateSend.get('/systemdate.json')
+ response = self.get('/systemdate.json')
Hashie::Mash.new(response)
end
# Gets valid timezones.
def timezones
- response = CreateSend.get('/timezones.json')
+ response = self.get('/timezones.json')
response.parsed_response
end
+ def authenticate!
+ self.class.basic_auth @api_key, 'x'
+ end
+
+ def get(*args)
+ authenticate!
+ self.class.get(*args)
+ end
+
+ def post(*args)
+ authenticate!
+ self.class.post(*args)
+ end
+
+ def put(*args)
+ authenticate!
+ self.class.put(*args)
+ end
+
+ def delete(*args)
+ authenticate!
+ self.class.delete(*args)
+ end
+
def self.get(*args); handle_response super end
def self.post(*args); handle_response super end
def self.put(*args); handle_response super end
@@ -133,4 +155,4 @@ def self.handle_response(response) # :nodoc:
end
end
end
-end
+end
View
14 lib/createsend/campaign.rb
@@ -6,13 +6,15 @@ module CreateSend
class Campaign
attr_reader :campaign_id
- def initialize(campaign_id)
+ def initialize(campaign_id, api_key)
@campaign_id = campaign_id
+ @api_key = api_key
+ @create_send = CreateSend.new(@api_key)
end
# Creates a new campaign for a client.
def self.create(client_id, subject, name, from_name, from_email, reply_to, html_url,
- text_url, list_ids, segment_ids)
+ text_url, list_ids, segment_ids, api_key)
options = { :body => {
:Subject => subject,
:Name => name,
@@ -23,7 +25,7 @@ def self.create(client_id, subject, name, from_name, from_email, reply_to, html_
:TextUrl => text_url,
:ListIDs => list_ids,
:SegmentIDs => segment_ids }.to_json }
- response = CreateSend.post "/campaigns/#{client_id}.json", options
+ response = CreateSend.new(api_key).post "/campaigns/#{client_id}.json", options
response.parsed_response
end
@@ -51,7 +53,7 @@ def unschedule
# Deletes this campaign.
def delete
- response = CreateSend.delete "/campaigns/#{campaign_id}.json", {}
+ response = @create_send.delete "/campaigns/#{campaign_id}.json", {}
end
# Gets a summary of this campaign
@@ -128,11 +130,11 @@ def bounces(date="1900-01-01", page=1, page_size=1000, order_field="date", order
private
def get(action, options = {})
- CreateSend.get uri_for(action), options
+ @create_send.get uri_for(action), options
end
def post(action, options = {})
- CreateSend.post uri_for(action), options
+ @create_send.post uri_for(action), options
end
def uri_for(action)
View
63 lib/createsend/client.rb
@@ -4,27 +4,44 @@
module CreateSend
# Represents a client and associated functionality.
class Client
+ attr_reader :api_key
attr_reader :client_id
+ attr_reader :username, :access_level
+ attr_reader :company_name, :contact_name, :email_address, :country, :time_zone
+ attr_reader :can_purchase_credits, :markup_on_design_spam_test, :client_pays, :base_rate_per_recipient,
+ :markup_per_recipient, :markup_on_delivery, :base_delivery_rate, :currency, :base_design_span_test_rate
- def initialize(client_id)
+ def initialize(client_id, api_key, with_details = false)
@client_id = client_id
+ @api_key = api_key
+ @create_send = CreateSend.new(@api_key)
+ details if with_details
end
- # Creates a client.
- def self.create(company, contact_name, email, timezone, country)
- options = { :body => {
- :CompanyName => company,
+ def self.create(company, contact_name, email, timezone, country, api_key)
+ options = { :body => {
+ :CompanyName => company,
:ContactName => contact_name,
:EmailAddress => email,
:TimeZone => timezone,
:Country => country }.to_json }
- CreateSend.post "/clients.json", options
+ CreateSend.new(api_key).post "/clients.json", options
end
# Gets the details of this client.
def details
- response = CreateSend.get "/clients/#{client_id}.json", {}
- Hashie::Mash.new(response)
+ response = @create_send.get "/clients/#{client_id}.json", {}
+
+ hash = Hashie::Mash.new(response)
+ combined_details = hash.select { |k, v|
+ [ "BasicDetails", "AccessDetails", "BillingDetails" ].include?(k)
+ }.values.reduce({}, &:merge)
+
+ combined_details.each do |k, v|
+ instance_variable_set :"@#{k.underscore}", v
+ end
+
+ hash
end
# Gets the sent campaigns belonging to this client.
@@ -32,7 +49,7 @@ def campaigns
response = get 'campaigns'
response.map{|item| Hashie::Mash.new(item)}
end
-
+
# Gets the currently scheduled campaigns belonging to this client.
def scheduled
response = get 'scheduled'
@@ -59,7 +76,7 @@ def segments
# Gets this client's suppression list.
def suppressionlist(page=1, page_size=1000, order_field="email", order_direction="asc")
- options = { :query => {
+ options = { :query => {
:page => page,
:pagesize => page_size,
:orderfield => order_field,
@@ -76,8 +93,8 @@ def templates
# Sets the basic details for this client.
def set_basics(company, contact_name, email, timezone, country)
- options = { :body => {
- :CompanyName => company,
+ options = { :body => {
+ :CompanyName => company,
:ContactName => contact_name,
:EmailAddress => email,
:TimeZone => timezone,
@@ -87,17 +104,17 @@ def set_basics(company, contact_name, email, timezone, country)
# Sets the access settings for this client.
def set_access(username, password, access_level)
- options = { :body => {
- :Username => username,
- :Password => password,
+ options = { :body => {
+ :Username => username,
+ :Password => password,
:AccessLevel => access_level }.to_json }
put 'setaccess', options
end
# Sets the PAYG billing settings for this client.
- def set_payg_billing(currency, can_purchase_credits, client_pays, markup_percentage,
+ def set_payg_billing(currency, can_purchase_credits, client_pays, markup_percentage,
markup_on_delivery=0, markup_per_recipient=0, markup_on_design_spam_test=0)
- options = { :body => {
+ options = { :body => {
:Currency => currency,
:CanPurchaseCredits => can_purchase_credits,
:ClientPays => client_pays,
@@ -110,7 +127,7 @@ def set_payg_billing(currency, can_purchase_credits, client_pays, markup_percent
# Sets the monthly billing settings for this client.
def set_monthly_billing(currency, client_pays, markup_percentage)
- options = { :body => {
+ options = { :body => {
:Currency => currency,
:ClientPays => client_pays,
:MarkupPercentage => markup_percentage }.to_json }
@@ -119,25 +136,25 @@ def set_monthly_billing(currency, client_pays, markup_percentage)
# Deletes this client.
def delete
- CreateSend.delete "/clients/#{client_id}.json", {}
+ @create_send.delete "/clients/#{client_id}.json", {}
end
private
def get(action, options = {})
- CreateSend.get uri_for(action), options
+ @create_send.get uri_for(action), options
end
def post(action, options = {})
- CreateSend.post uri_for(action), options
+ @create_send.post uri_for(action), options
end
def put(action, options = {})
- CreateSend.put uri_for(action), options
+ @create_send.put uri_for(action), options
end
def uri_for(action)
"/clients/#{client_id}/#{action}.json"
end
end
-end
+end
View
46 lib/createsend/list.rb
@@ -4,26 +4,29 @@
module CreateSend
# Represents a subscriber list and associated functionality.
class List
- attr_reader :list_id
+ attr_reader :list_id, :title, :confirmed_opt_in, :unsubscribe_page, :confirmation_success_page
- def initialize(list_id)
+ def initialize(list_id, api_key, with_details = false)
@list_id = list_id
+ @api_key = api_key
+ @create_send = CreateSend.new(@api_key)
+ details if with_details
end
# Creates a new list for a client.
- def self.create(client_id, title, unsubscribe_page, confirmed_opt_in, confirmation_success_page)
+ def self.create(client_id, title, unsubscribe_page, confirmed_opt_in, confirmation_success_page, api_key)
options = { :body => {
:Title => title,
:UnsubscribePage => unsubscribe_page,
:ConfirmedOptIn => confirmed_opt_in,
:ConfirmationSuccessPage => confirmation_success_page }.to_json }
- response = CreateSend.post "/lists/#{client_id}.json", options
+ response = CreateSend.new(api_key).post "/lists/#{client_id}.json", options
response.parsed_response
end
# Deletes this list.
def delete
- response = CreateSend.delete "/lists/#{list_id}.json", {}
+ response = @create_send.delete "/lists/#{list_id}.json", {}
end
# Creates a new custom field for this list.
@@ -39,7 +42,7 @@ def create_custom_field(field_name, data_type, options=[])
# Deletes a custom field associated with this list.
def delete_custom_field(custom_field_key)
custom_field_key = CGI.escape(custom_field_key)
- response = CreateSend.delete "/lists/#{list_id}/customfields/#{custom_field_key}.json", {}
+ response = @create_send.delete "/lists/#{list_id}/customfields/#{custom_field_key}.json", {}
end
# Updates the options of a multi-optioned custom field on this list.
@@ -53,8 +56,13 @@ def update_custom_field_options(custom_field_key, new_options, keep_existing_opt
# Gets the details of this list.
def details
- response = CreateSend.get "/lists/#{list_id}.json", {}
- Hashie::Mash.new(response)
+ response = @create_send.get "/lists/#{list_id}.json", {}
+ hash = Hashie::Mash.new(response)
+ hash.each do |k, v|
+ instance_variable_set :"@#{k.underscore}", v
+ end
+
+ hash
end
# Gets the custom fields for this list.
@@ -77,7 +85,7 @@ def stats
# Gets the active subscribers for this list.
def active(date, page=1, page_size=1000, order_field="email", order_direction="asc")
- options = { :query => {
+ options = { :query => {
:date => date,
:page => page,
:pagesize => page_size,
@@ -89,7 +97,7 @@ def active(date, page=1, page_size=1000, order_field="email", order_direction="a
# Gets the bounced subscribers for this list.
def bounced(date, page=1, page_size=1000, order_field="email", order_direction="asc")
- options = { :query => {
+ options = { :query => {
:date => date,
:page => page,
:pagesize => page_size,
@@ -101,7 +109,7 @@ def bounced(date, page=1, page_size=1000, order_field="email", order_direction="
# Gets the unsubscribed subscribers for this list.
def unsubscribed(date, page=1, page_size=1000, order_field="email", order_direction="asc")
- options = { :query => {
+ options = { :query => {
:date => date,
:page => page,
:pagesize => page_size,
@@ -113,7 +121,7 @@ def unsubscribed(date, page=1, page_size=1000, order_field="email", order_direct
# Gets the deleted subscribers for this list.
def deleted(date, page=1, page_size=1000, order_field="email", order_direction="asc")
- options = { :query => {
+ options = { :query => {
:date => date,
:page => page,
:pagesize => page_size,
@@ -130,7 +138,7 @@ def update(title, unsubscribe_page, confirmed_opt_in, confirmation_success_page)
:UnsubscribePage => unsubscribe_page,
:ConfirmedOptIn => confirmed_opt_in,
:ConfirmationSuccessPage => confirmation_success_page }.to_json }
- response = CreateSend.put "/lists/#{list_id}.json", options
+ response = @create_send.put "/lists/#{list_id}.json", options
end
# Gets the webhooks for this list.
@@ -139,7 +147,7 @@ def webhooks
response.map{|item| Hashie::Mash.new(item)}
end
- # Creates a new webhook for the specified events (an array of strings).
+ # Creates a new webhook for the specified events (an array of strings).
# Valid events are "Subscribe", "Deactivate", and "Update".
# Valid payload formats are "json", and "xml".
def create_webhook(events, url, payload_format)
@@ -160,7 +168,7 @@ def test_webhook(webhook_id)
# Deletes a webhook associated with this list.
def delete_webhook(webhook_id)
- response = CreateSend.delete "/lists/#{list_id}/webhooks/#{webhook_id}.json", {}
+ response = @create_send.delete "/lists/#{list_id}/webhooks/#{webhook_id}.json", {}
end
# Activates a webhook associated with this list.
@@ -178,15 +186,15 @@ def deactivate_webhook(webhook_id)
private
def get(action, options = {})
- CreateSend.get uri_for(action), options
+ @create_send.get uri_for(action), options
end
def post(action, options = {})
- CreateSend.post uri_for(action), options
+ @create_send.post uri_for(action), options
end
def put(action, options = {})
- CreateSend.put uri_for(action), options
+ @create_send.put uri_for(action), options
end
def uri_for(action)
@@ -194,4 +202,4 @@ def uri_for(action)
end
end
-end
+end
View
39 lib/createsend/segment.rb
@@ -4,18 +4,21 @@
module CreateSend
# Represents a subscriber list segment and associated functionality.
class Segment
- attr_reader :segment_id
+ attr_reader :segment_id, :active_subscribers, :rules, :list_id, :title
- def initialize(segment_id)
+ def initialize(segment_id, api_key, with_details = false)
@segment_id = segment_id
+ @api_key = api_key
+ @create_send = CreateSend.new(@api_key)
+ details if with_details
end
# Creates a new segment.
- def self.create(list_id, title, rules)
+ def self.create(list_id, title, rules, api_key)
options = { :body => {
:Title => title,
:Rules => rules }.to_json }
- response = CreateSend.post "/segments/#{list_id}.json", options
+ response = CreateSend.new(api_key).post "/segments/#{list_id}.json", options
response.parsed_response
end
@@ -24,7 +27,7 @@ def update(title, rules)
options = { :body => {
:Title => title,
:Rules => rules }.to_json }
- response = CreateSend.put "/segments/#{segment_id}.json", options
+ response = @create_send.put "/segments/#{segment_id}.json", options
end
# Adds a rule to this segment.
@@ -32,7 +35,7 @@ def add_rule(subject, clauses)
options = { :body => {
:Subject => subject,
:Clauses => clauses }.to_json }
- response = CreateSend.post "/segments/#{segment_id}/rules.json", options
+ response = @create_send.post "/segments/#{segment_id}/rules.json", options
end
# Gets the active subscribers in this segment.
@@ -49,32 +52,38 @@ def subscribers(date, page=1, page_size=1000, order_field="email", order_directi
# Gets the details of this segment
def details
- response = CreateSend.get "/segments/#{segment_id}.json", {}
- Hashie::Mash.new(response)
+ response = @create_send.get "/segments/#{segment_id}.json", {}
+ hash = Hashie::Mash.new(response)
+
+ hash.each do |k,v|
+ instance_variable_set :"@#{k.underscore}", v
+ end
+
+ hash
end
# Clears all rules of this segment.
def clear_rules
- response = CreateSend.delete "/segments/#{segment_id}/rules.json", {}
+ response = @create_send.delete "/segments/#{segment_id}/rules.json", {}
end
# Deletes this segment.
def delete
- response = CreateSend.delete "/segments/#{segment_id}.json", {}
+ response = @create_send.delete "/segments/#{segment_id}.json", {}
end
-
+
private
def get(action, options = {})
- CreateSend.get uri_for(action), options
+ @create_send.get uri_for(action), options
end
def post(action, options = {})
- CreateSend.post uri_for(action), options
+ @create_send.post uri_for(action), options
end
def put(action, options = {})
- CreateSend.put uri_for(action), options
+ @create_send.put uri_for(action), options
end
def uri_for(action)
@@ -82,4 +91,4 @@ def uri_for(action)
end
end
-end
+end
View
24 lib/createsend/subscriber.rb
@@ -7,37 +7,39 @@ class Subscriber
attr_reader :list_id
attr_reader :email_address
- def initialize(list_id, email_address)
+ def initialize(list_id, email_address, api_key)
@list_id = list_id
@email_address = email_address
+ @api_key = api_key
+ @create_send = CreateSend.new(api_key)
end
# Gets a subscriber by list ID and email address.
- def self.get(list_id, email_address)
+ def self.get(list_id, email_address, api_key)
options = { :query => { :email => email_address } }
- response = CreateSend.get "/subscribers/#{list_id}.json", options
+ response = CreateSend.new(api_key).get "/subscribers/#{list_id}.json", options
Hashie::Mash.new(response)
end
# Adds a subscriber to a subscriber list.
- def self.add(list_id, email_address, name, custom_fields, resubscribe)
+ def self.add(list_id, email_address, name, custom_fields, resubscribe, api_key)
options = { :body => {
:EmailAddress => email_address,
:Name => name,
:CustomFields => custom_fields,
:Resubscribe => resubscribe }.to_json }
- response = CreateSend.post "/subscribers/#{list_id}.json", options
+ response = CreateSend.new(api_key).post "/subscribers/#{list_id}.json", options
response.parsed_response
end
# Imports subscribers into a subscriber list.
- def self.import(list_id, subscribers, resubscribe, queue_subscription_based_autoresponders=false)
+ def self.import(list_id, subscribers, resubscribe, queue_subscription_based_autoresponders, api_key)
options = { :body => {
:Subscribers => subscribers,
:Resubscribe => resubscribe,
:QueueSubscriptionBasedAutoresponders => queue_subscription_based_autoresponders }.to_json }
begin
- response = CreateSend.post "/subscribers/#{list_id}/import.json", options
+ response = CreateSend.new(api_key).post "/subscribers/#{list_id}/import.json", options
rescue BadRequest => br
# Subscriber import will throw BadRequest if some subscribers are not imported
# successfully. If this occurs, we want to return the ResultData property of
@@ -62,7 +64,7 @@ def update(new_email_address, name, custom_fields, resubscribe)
:Name => name,
:CustomFields => custom_fields,
:Resubscribe => resubscribe }.to_json }
- CreateSend.put "/subscribers/#{@list_id}.json", options
+ @create_send.put "/subscribers/#{@list_id}.json", options
# Update @email_address, so this object can continue to be used reliably
@email_address = new_email_address
end
@@ -71,20 +73,20 @@ def update(new_email_address, name, custom_fields, resubscribe)
def unsubscribe
options = { :body => {
:EmailAddress => @email_address }.to_json }
- CreateSend.post "/subscribers/#{@list_id}/unsubscribe.json", options
+ @create_send.post "/subscribers/#{@list_id}/unsubscribe.json", options
end
# Gets the historical record of this subscriber's trackable actions.
def history
options = { :query => { :email => @email_address } }
- response = CreateSend.get "/subscribers/#{@list_id}/history.json", options
+ response = @create_send.get "/subscribers/#{@list_id}/history.json", options
response.map{|item| Hashie::Mash.new(item)}
end
# Moves this subscriber to the Deleted state in the associated list.
def delete
options = { :query => { :email => @email_address } }
- CreateSend.delete "/subscribers/#{@list_id}.json", options
+ @create_send.delete "/subscribers/#{@list_id}.json", options
end
end
end
View
14 lib/createsend/template.rb
@@ -6,23 +6,25 @@ module CreateSend
class Template
attr_reader :template_id
- def initialize(template_id)
+ def initialize(template_id, api_key)
+ @api_key = api_key
@template_id = template_id
+ @create_send = CreateSend.new(@api_key)
end
# Creates a new email template.
- def self.create(client_id, name, html_url, zip_url)
+ def self.create(client_id, name, html_url, zip_url, api_key)
options = { :body => {
:Name => name,
:HtmlPageURL => html_url,
:ZipFileURL => zip_url }.to_json }
- response = CreateSend.post "/templates/#{client_id}.json", options
+ response = CreateSend.new(api_key).post "/templates/#{client_id}.json", options
response.parsed_response
end
# Gets the details of this email template.
def details
- response = CreateSend.get "/templates/#{template_id}.json", {}
+ response = @create_send.get "/templates/#{template_id}.json", {}
Hashie::Mash.new(response)
end
@@ -32,12 +34,12 @@ def update(name, html_url, zip_url)
:Name => name,
:HtmlPageURL => html_url,
:ZipFileURL => zip_url }.to_json }
- response = CreateSend.put "/templates/#{template_id}.json", options
+ response = @create_send.put "/templates/#{template_id}.json", options
end
# Deletes this email template.
def delete
- response = CreateSend.delete "/templates/#{template_id}.json", {}
+ response = @create_send.delete "/templates/#{template_id}.json", {}
end
end
end
View
5 test/campaign_test.rb
@@ -4,8 +4,7 @@ class CampaignTest < Test::Unit::TestCase
context "when an api caller is authenticated" do
setup do
@api_key = '123123123123123123123'
- CreateSend.api_key @api_key
- @campaign = CreateSend::Campaign.new('787y87y87y87y87y87y87')
+ @campaign = CreateSend::Campaign.new('787y87y87y87y87y87y87', @api_key)
end
should "create a campaign" do
@@ -13,7 +12,7 @@ class CampaignTest < Test::Unit::TestCase
stub_post(@api_key, "campaigns/#{client_id}.json", "create_campaign.json")
campaign_id = CreateSend::Campaign.create client_id, "subject", "name", "g'day", "good.day@example.com", "good.day@example.com",
"http://example.com/campaign.html", "http://example.com/campaign.txt", [ '7y12989e82ue98u2e', 'dh9w89q8w98wudwd989' ],
- [ 'y78q9w8d9w8ud9q8uw', 'djw98quw9duqw98uwd98' ]
+ [ 'y78q9w8d9w8ud9q8uw', 'djw98quw9duqw98uwd98' ], @api_key
campaign_id.should == "787y87y87y87y87y87y87"
end
View
38 test/client_test.rb
@@ -4,17 +4,19 @@ class ClientTest < Test::Unit::TestCase
context "when an api caller is authenticated" do
setup do
@api_key = '123123123123123123123'
- CreateSend.api_key @api_key
- @client = CreateSend::Client.new('321iuhiuhi1u23hi2u3')
+ #CreateSend.api_key @api_key
+ @client = CreateSend::Client.new('321iuhiuhi1u23hi2u3', @api_key)
@client.client_id.should == '321iuhiuhi1u23hi2u3'
+ @client.api_key.should == '123123123123123123123'
end
should "create a client" do
stub_post(@api_key, "clients.json", "create_client.json")
- client_id = CreateSend::Client.create "Client Company Name", "Client Contact Name", "client@example.com", "(GMT+10:00) Canberra, Melbourne, Sydney", "Australia"
+ client_id = CreateSend::Client.create "Client Company Name", "Client Contact Name", "client@example.com", "(GMT+10:00) Canberra, Melbourne, Sydney",
+ "Australia", @api_key
client_id.should == "32a381c49a2df99f1d0c6f3c112352b9"
end
-
+
should "get details of a client" do
stub_get(@api_key, "clients/#{@client.client_id}.json", "client_details.json")
cl = @client.details
@@ -25,6 +27,20 @@ class ClientTest < Test::Unit::TestCase
cl.AccessDetails.AccessLevel.should == 23
end
+ should "set attributes when getting details" do
+ stub_get(@api_key, "clients/#{@client.client_id}.json", "client_details.json")
+
+ cl = @client.details
+ @client.client_id.should == cl.BasicDetails.ClientID
+ @client.contact_name.should == cl.BasicDetails.ContactName
+
+ @client.username.should == cl.AccessDetails.Username
+ @client.access_level.should == cl.AccessDetails.AccessLevel
+
+ @client.can_purchase_credits.should == cl.BillingDetails.CanPurchaseCredits
+ @client.markup_on_design_spam_test.should == cl.BillingDetails.MarkupOnDesignSpamTest
+ end
+
should "get all campaigns" do
stub_get(@api_key, "clients/#{@client.client_id}/campaigns.json", "campaigns.json")
campaigns = @client.campaigns
@@ -68,7 +84,7 @@ class ClientTest < Test::Unit::TestCase
lists.first.ListID.should == 'a58ee1d3039b8bec838e6d1482a8a965'
lists.first.Name.should == 'List One'
end
-
+
should "get all segments for a client" do
stub_get(@api_key, "clients/#{@client.client_id}/segments.json", "segments.json")
segments = @client.segments
@@ -102,31 +118,31 @@ class ClientTest < Test::Unit::TestCase
templates.first.TemplateID.should == '5cac213cf061dd4e008de5a82b7a3621'
templates.first.Name.should == 'Template One'
end
-
+
should "set basics" do
stub_put(@api_key, "clients/#{@client.client_id}/setbasics.json", nil)
@client.set_basics "Client Company Name", "Client Contact Name", "client@example.com", "(GMT+10:00) Canberra, Melbourne, Sydney", "Australia"
end
-
+
should "set access" do
stub_put(@api_key, "clients/#{@client.client_id}/setaccess.json", nil)
@client.set_access "username", "password", 321
end
-
+
should "set payg billing" do
stub_put(@api_key, "clients/#{@client.client_id}/setpaygbilling.json", nil)
@client.set_payg_billing "CAD", true, true, 150
end
-
+
should "set monthly billing" do
stub_put(@api_key, "clients/#{@client.client_id}/setmonthlybilling.json", nil)
@client.set_monthly_billing "CAD", true, 150
end
-
+
should "delete a client" do
stub_delete(@api_key, "clients/#{@client.client_id}.json", nil)
@client.delete
end
-
+
end
end
View
24 test/createsend_test.rb
@@ -5,10 +5,9 @@ class CreateSendTest < Test::Unit::TestCase
setup do
@api_key = '123123123123123123123'
@base_uri = 'https://api.createsend.com/api/v3'
- CreateSend.api_key @api_key
- @cs = CreateSend::CreateSend.new
+ @cs = CreateSend.new(@api_key)
end
-
+
should "include the CreateSend module VERSION constant as part of the user agent when making a call" do
# This test is done to ensure that the version from HTTParty isn't included instead
assert CreateSend::CreateSend.headers["User-Agent"] == "createsend-ruby-#{CreateSend::VERSION}"
@@ -16,7 +15,7 @@ class CreateSendTest < Test::Unit::TestCase
clients = @cs.clients
clients.size.should == 2
end
-
+
should "get api key" do
uri = URI.parse(@base_uri)
site_url = "http://iamadesigner.createsend.com/"
@@ -34,14 +33,14 @@ class CreateSendTest < Test::Unit::TestCase
clients.first.ClientID.should == '4a397ccaaa55eb4e6aa1221e1e2d7122'
clients.first.Name.should == 'Client One'
end
-
+
should "get all countries" do
stub_get(@api_key, "countries.json", "countries.json")
countries = @cs.countries
countries.size.should == 245
assert countries.include? "Australia"
end
-
+
should "get system date" do
stub_get(@api_key, "systemdate.json", "systemdate.json")
systemdate = @cs.systemdate.SystemDate
@@ -60,11 +59,10 @@ class CreateSendTest < Test::Unit::TestCase
setup do
@api_key = '123123123123123123123'
@base_uri = 'https://api.createsend.com/api/v3'
- CreateSend.api_key @api_key
- @cs = CreateSend::CreateSend.new
- @template = CreateSend::Template.new('98y2e98y289dh89h938389')
+ @cs = CreateSend::CreateSend.new(@api_key)
+ @template = CreateSend::Template.new('98y2e98y289dh89h938389', @api_key)
end
-
+
{ ["400", "Bad Request"] => CreateSend::BadRequest,
["401", "Unauthorized"] => CreateSend::Unauthorized,
["404", "Not Found"] => CreateSend::NotFound,
@@ -80,15 +78,15 @@ class CreateSendTest < Test::Unit::TestCase
context "#{status.first}, a post" do
should "raise a #{exception.name} error" do
stub_post(@api_key, "clients.json", (status.first == '400' or status.first == '401') ? 'custom_api_error.json' : nil, status)
- lambda { CreateSend::Client.create "Client Company Name", "Client Contact Name", "client@example.com",
- "(GMT+10:00) Canberra, Melbourne, Sydney", "Australia" }.should raise_error(exception)
+ lambda { CreateSend::Client.create "Client Company Name", "Client Contact Name", "client@example.com",
+ "(GMT+10:00) Canberra, Melbourne, Sydney", "Australia", @api_key }.should raise_error(exception)
end
end
context "#{status.first}, a put" do
should "raise a #{exception.name} error" do
stub_put(@api_key, "templates/#{@template.template_id}.json", (status.first == '400' or status.first == '401') ? 'custom_api_error.json' : nil, status)
- lambda { @template.update "Template One Updated", "http://templates.org/index.html",
+ lambda { @template.update "Template One Updated", "http://templates.org/index.html",
"http://templates.org/files.zip" }.should raise_error(exception)
end
end
View
36 test/list_test.rb
@@ -4,15 +4,14 @@ class ListTest < Test::Unit::TestCase
context "when an api caller is authenticated" do
setup do
@api_key = '123123123123123123123'
- CreateSend.api_key @api_key
@client_id = "87y8d7qyw8d7yq8w7ydwqwd"
@list_id = "e3c5f034d68744f7881fdccf13c2daee"
- @list = CreateSend::List.new @list_id
+ @list = CreateSend::List.new @list_id, @api_key
end
should "create a list" do
- stub_post(@api_key, "lists/#{@client_id}.json", "create_list.json")
- list_id = CreateSend::List.create @client_id, "List One", "", false, ""
+ stub_post(@api_key, "lists/#{@client_id}.json", "create_list.json", @api_key)
+ list_id = CreateSend::List.create @client_id, "List One", "", false, "", @api_key
list_id.should == "e3c5f034d68744f7881fdccf13c2daee"
end
@@ -37,7 +36,7 @@ class ListTest < Test::Unit::TestCase
stub_delete(@api_key, "lists/#{@list.list_id}/customfields/#{CGI.escape(custom_field_key)}.json", nil)
@list.delete_custom_field custom_field_key
end
-
+
should "update the options of a multi-optioned custom field" do
custom_field_key = "[newdatefield]"
new_options = [ "one", "two", "three" ]
@@ -55,6 +54,17 @@ class ListTest < Test::Unit::TestCase
details.ConfirmationSuccessPage.should == ""
end
+ should "set attributes when getting details" do
+ stub_get(@api_key, "lists/#{@list.list_id}.json", "list_details.json")
+
+ details = @list.details
+ @list.list_id.should == details.ListID
+ @list.title.should == details.Title
+ @list.confirmed_opt_in.should == details.ConfirmedOptIn
+ @list.unsubscribe_page.should == details.UnsubscribePage
+ @list.confirmation_success_page.should == details.ConfirmationSuccessPage
+ end
+
should "get the custom fields for a list" do
stub_get(@api_key, "lists/#{@list.list_id}/customfields.json", "custom_fields.json")
cfs = @list.custom_fields
@@ -73,7 +83,7 @@ class ListTest < Test::Unit::TestCase
segments.first.SegmentID.should == '46aa5e01fd43381863d4e42cf277d3a9'
segments.first.Title.should == 'Segment One'
end
-
+
should "get the stats for a list" do
stub_get(@api_key, "lists/#{@list.list_id}/stats.json", "list_stats.json")
stats = @list.stats
@@ -82,7 +92,7 @@ class ListTest < Test::Unit::TestCase
stats.TotalDeleted.should == 0
stats.TotalBounces.should == 0
end
-
+
should "get the active subscribers for a list" do
min_date = "2010-01-01"
stub_get(@api_key, "lists/#{@list.list_id}/active.json?pagesize=1000&orderfield=email&page=1&orderdirection=asc&date=#{CGI.escape(min_date)}",
@@ -102,10 +112,10 @@ class ListTest < Test::Unit::TestCase
res.Results.first.State.should == "Active"
res.Results.first.CustomFields.size.should == 3
end
-
+
should "get the unsubscribed subscribers for a list" do
min_date = "2010-01-01"
- stub_get(@api_key, "lists/#{@list.list_id}/unsubscribed.json?pagesize=1000&orderfield=email&page=1&orderdirection=asc&date=#{CGI.escape(min_date)}",
+ stub_get(@api_key, "lists/#{@list.list_id}/unsubscribed.json?pagesize=1000&orderfield=email&page=1&orderdirection=asc&date=#{CGI.escape(min_date)}",
"unsubscribed_subscribers.json")
res = @list.unsubscribed min_date
res.ResultsOrderedBy.should == "email"
@@ -125,7 +135,7 @@ class ListTest < Test::Unit::TestCase
should "get the deleted subscribers for a list" do
min_date = "2010-01-01"
- stub_get(@api_key, "lists/#{@list.list_id}/deleted.json?pagesize=1000&orderfield=email&page=1&orderdirection=asc&date=#{CGI.escape(min_date)}",
+ stub_get(@api_key, "lists/#{@list.list_id}/deleted.json?pagesize=1000&orderfield=email&page=1&orderdirection=asc&date=#{CGI.escape(min_date)}",
"deleted_subscribers.json")
res = @list.deleted min_date
res.ResultsOrderedBy.should == "email"
@@ -180,7 +190,7 @@ class ListTest < Test::Unit::TestCase
webhook_id = @list.create_webhook ["Unsubscribe", "Spam"], "http://example.com/unsub", "json"
webhook_id.should == "6a783d359bd44ef62c6ca0d3eda4412a"
end
-
+
should "test a webhook for a list" do
webhook_id = "jiuweoiwueoiwueowiueo"
stub_get(@api_key, "lists/#{@list.list_id}/webhooks/#{webhook_id}/test.json", nil)
@@ -192,7 +202,7 @@ class ListTest < Test::Unit::TestCase
stub_delete(@api_key, "lists/#{@list.list_id}/webhooks/#{webhook_id}.json", nil)
@list.delete_webhook webhook_id
end
-
+
should "activate a webhook for a list" do
webhook_id = "jiuweoiwueoiwueowiueo"
stub_put(@api_key, "lists/#{@list.list_id}/webhooks/#{webhook_id}/activate.json", nil)
@@ -205,4 +215,4 @@ class ListTest < Test::Unit::TestCase
@list.deactivate_webhook webhook_id
end
end
-end
+end
View
20 test/segment_test.rb
@@ -4,15 +4,14 @@ class SegmentTest < Test::Unit::TestCase
context "when an api caller is authenticated" do
setup do
@api_key = '123123123123123123123'
- CreateSend.api_key @api_key
- @segment = CreateSend::Segment.new('98y2e98y289dh89h938389')
+ @segment = CreateSend::Segment.new('98y2e98y289dh89h938389', @api_key)
end
should "create a new segment" do
list_id = "2983492834987394879837498"
rules = [ { :Subject => "EmailAddress", :Clauses => [ "CONTAINS example.com" ] } ]
stub_post(@api_key, "segments/#{list_id}.json", "create_segment.json")
- res = CreateSend::Segment.create list_id, "new segment title", rules
+ res = CreateSend::Segment.create list_id, "new segment title", rules, @api_key
res.should == "0246c2aea610a3545d9780bf6ab89006"
end
@@ -21,7 +20,7 @@ class SegmentTest < Test::Unit::TestCase
stub_put(@api_key, "segments/#{@segment.segment_id}.json", nil)
@segment.update "new title for segment", rules
end
-
+
should "add a rule to a segment" do
clauses = [ "CONTAINS example.com" ]
stub_post(@api_key, "segments/#{@segment.segment_id}/rules.json", nil)
@@ -47,7 +46,7 @@ class SegmentTest < Test::Unit::TestCase
res.Results.first.State.should == "Active"
res.Results.first.CustomFields.should == []
end
-
+
should "delete a segment" do
stub_delete(@api_key, "segments/#{@segment.segment_id}.json", nil)
@segment.delete
@@ -66,6 +65,17 @@ class SegmentTest < Test::Unit::TestCase
res.Title.should == "My Segment"
end
+ should "set attributes when getting details" do
+ stub_get(@api_key, "segments/#{@segment.segment_id}.json", "segment_details.json")
+
+ details = @segment.details
+ @segment.active_subscribers.should == details.ActiveSubscribers
+ @segment.rules.should == details.Rules
+ @segment.list_id.should == details.ListID
+ @segment.segment_id.should == details.SegmentID
+ @segment.title.should == details.Title
+ end
+
should "clear a segment's rules" do
stub_delete(@api_key, "segments/#{@segment.segment_id}/rules.json", nil)
@segment.clear_rules
View
19 test/subscriber_test.rb
@@ -4,15 +4,14 @@ class SubscriberTest < Test::Unit::TestCase
context "when an api caller is authenticated" do
setup do
@api_key = '123123123123123123123'
- CreateSend.api_key @api_key
@list_id = "d98h2938d9283d982u3d98u88"
- @subscriber = CreateSend::Subscriber.new @list_id, "subscriber@example.com"
+ @subscriber = CreateSend::Subscriber.new @list_id, "subscriber@example.com", @api_key
end
should "get a subscriber by list id and email address" do
email = "subscriber@example.com"
stub_get(@api_key, "subscribers/#{@list_id}.json?email=#{CGI.escape(email)}", "subscriber_details.json")
- subscriber = CreateSend::Subscriber.get @list_id, email
+ subscriber = CreateSend::Subscriber.get @list_id, email, @api_key
subscriber.EmailAddress.should == email
subscriber.Name.should == "Subscriber One"
subscriber.Date.should == "2010-10-25 10:28:00"
@@ -24,14 +23,14 @@ class SubscriberTest < Test::Unit::TestCase
should "add a subscriber without custom fields" do
stub_post(@api_key, "subscribers/#{@list_id}.json", "add_subscriber.json")
- email_address = CreateSend::Subscriber.add @list_id, "subscriber@example.com", "Subscriber", [], true
+ email_address = CreateSend::Subscriber.add @list_id, "subscriber@example.com", "Subscriber", [], true, @api_key
email_address.should == "subscriber@example.com"
end
should "add a subscriber with custom fields" do
stub_post(@api_key, "subscribers/#{@list_id}.json", "add_subscriber.json")
custom_fields = [ { :Key => 'website', :Value => 'http://example.com/' } ]
- email_address = CreateSend::Subscriber.add @list_id, "subscriber@example.com", "Subscriber", custom_fields, true
+ email_address = CreateSend::Subscriber.add @list_id, "subscriber@example.com", "Subscriber", custom_fields, true, @api_key
email_address.should == "subscriber@example.com"
end
@@ -40,7 +39,7 @@ class SubscriberTest < Test::Unit::TestCase
custom_fields = [ { :Key => 'multioptionselectone', :Value => 'myoption' },
{ :Key => 'multioptionselectmany', :Value => 'firstoption' },
{ :Key => 'multioptionselectmany', :Value => 'secondoption' } ]
- email_address = CreateSend::Subscriber.add @list_id, "subscriber@example.com", "Subscriber", custom_fields, true
+ email_address = CreateSend::Subscriber.add @list_id, "subscriber@example.com", "Subscriber", custom_fields, true, @api_key
email_address.should == "subscriber@example.com"
end
@@ -69,7 +68,7 @@ class SubscriberTest < Test::Unit::TestCase
{ :EmailAddress => "example+2@example.com", :Name => "Example Two" },
{ :EmailAddress => "example+3@example.com", :Name => "Example Three" },
]
- import_result = CreateSend::Subscriber.import @list_id, subscribers, true
+ import_result = CreateSend::Subscriber.import @list_id, subscribers, true, false, @api_key
import_result.FailureDetails.size.should == 0
import_result.TotalUniqueEmailsSubmitted.should == 3
import_result.TotalExistingSubscribers.should == 0
@@ -84,7 +83,7 @@ class SubscriberTest < Test::Unit::TestCase
{ :EmailAddress => "example+2@example.com", :Name => "Example Two" },
{ :EmailAddress => "example+3@example.com", :Name => "Example Three" },
]
- import_result = CreateSend::Subscriber.import @list_id, subscribers, true, true
+ import_result = CreateSend::Subscriber.import @list_id, subscribers, true, true, @api_key
import_result.FailureDetails.size.should == 0
import_result.TotalUniqueEmailsSubmitted.should == 3
import_result.TotalExistingSubscribers.should == 0
@@ -99,7 +98,7 @@ class SubscriberTest < Test::Unit::TestCase
{ :EmailAddress => "example+2@example.com", :Name => "Example Two", :CustomFields => [ { :Key => 'website', :Value => '', :Clear => false } ] },
{ :EmailAddress => "example+3@example.com", :Name => "Example Three", :CustomFields => [ { :Key => 'website', :Value => '', :Clear => false } ] },
]
- import_result = CreateSend::Subscriber.import @list_id, subscribers, true
+ import_result = CreateSend::Subscriber.import @list_id, subscribers, true, false, @api_key
import_result.FailureDetails.size.should == 0
import_result.TotalUniqueEmailsSubmitted.should == 3
import_result.TotalExistingSubscribers.should == 0
@@ -115,7 +114,7 @@ class SubscriberTest < Test::Unit::TestCase
{ :EmailAddress => "example+2@example.com", :Name => "Example Two" },
{ :EmailAddress => "example+3@example.com", :Name => "Example Three" },
]
- import_result = CreateSend::Subscriber.import @list_id, subscribers, true
+ import_result = CreateSend::Subscriber.import @list_id, subscribers, true, false, @api_key
import_result.FailureDetails.size.should == 1
import_result.FailureDetails.first.EmailAddress.should == "example+1@example"
import_result.FailureDetails.first.Code.should == 1
View
5 test/template_test.rb
@@ -4,15 +4,14 @@ class TemplateTest < Test::Unit::TestCase
context "when an api caller is authenticated" do
setup do
@api_key = '123123123123123123123'
- CreateSend.api_key @api_key
- @template = CreateSend::Template.new('98y2e98y289dh89h938389')
+ @template = CreateSend::Template.new('98y2e98y289dh89h938389', @api_key)
end
should "create a template" do
client_id = '87y8d7qyw8d7yq8w7ydwqwd'
stub_post(@api_key, "templates/#{client_id}.json", "create_template.json")
template_id = CreateSend::Template.create client_id, "Template One", "http://templates.org/index.html",
- "http://templates.org/files.zip"
+ "http://templates.org/files.zip", @api_key
template_id.should == "98y2e98y289dh89h938389"
end
Something went wrong with that request. Please try again.