salesmachine-ruby 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 2f0584bc2d15b7a36cbc2ecc133e6ddff1020e6f
4
+ data.tar.gz: 77ec6eeebc0237756882ec961253541be88f8bef
5
+ SHA512:
6
+ metadata.gz: 671f204499056ffeb4519b5f105908d22ed58d4bd6058fdcb25773134c3b13ccf063c3af62d7dd81323b2707ec6efa82a7d4ad3dabf36d84fc0084da67a4ce46
7
+ data.tar.gz: a6f2203974ef6c6e59f590de46242ad6e7e7d97b55a062f2206e9202bf599f2bcfad75db5b564364d3d53ea06b560ebfc114f3de8ee5315cfa89fc82c43bb4b2
@@ -0,0 +1,9 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
@@ -0,0 +1,13 @@
1
+ # Contributor Code of Conduct
2
+
3
+ As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.
4
+
5
+ We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, or religion.
6
+
7
+ Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct.
8
+
9
+ Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team.
10
+
11
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers.
12
+
13
+ This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.0.0, available at [http://contributor-covenant.org/version/1/0/0/](http://contributor-covenant.org/version/1/0/0/)
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in salesmachine-ruby.gemspec
4
+ gemspec
data/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2015 citizen75
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1,32 @@
1
+ # Salesmachine::Ruby
2
+
3
+ Salesmachine.io client ruby gem library
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'salesmachine-ruby'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install salesmachine-ruby
20
+
21
+ ## Usage
22
+
23
+ see [Salesmachine documentation](http://doc.salesmachine.io/docs/authentification)
24
+
25
+ ## Contributing
26
+
27
+ Bug reports and pull requests are welcome on GitHub at https://github.com/salesmachine-io/salesmachine-ruby. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](contributor-covenant.org) code of conduct.
28
+
29
+
30
+ ## License
31
+
32
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "salesmachine/ruby"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start
@@ -0,0 +1,7 @@
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+
5
+ bundle install
6
+
7
+ # Do any other automated setup that you need to do here
@@ -0,0 +1 @@
1
+ require 'salesmachine/api'
@@ -0,0 +1,32 @@
1
+ require 'salesmachine/api/version'
2
+
3
+ require 'salesmachine/api/config'
4
+ require 'salesmachine/api/utils'
5
+ require 'salesmachine/api/client'
6
+ require 'salesmachine/api/worker'
7
+ require 'salesmachine/api/request'
8
+ require 'salesmachine/api/response'
9
+ require 'salesmachine/api/logging'
10
+
11
+ module Salesmachine
12
+ class Api
13
+ def initialize(options = {})
14
+ Request.stub = options[:stub]
15
+ @client = Salesmachine::Api::Client.new options
16
+ end
17
+
18
+ def method_missing(message, *args, &block)
19
+ if @client.respond_to? message
20
+ @client.send message, *args, &block
21
+ else
22
+ super
23
+ end
24
+ end
25
+
26
+ def respond_to?(method_name, include_private = false)
27
+ @client.respond_to?(method_name) || super
28
+ end
29
+
30
+ include Logging
31
+ end
32
+ end
@@ -0,0 +1,223 @@
1
+ require 'thread'
2
+ require 'time'
3
+ require 'salesmachine/api/utils'
4
+ require 'salesmachine/api/worker'
5
+ require 'salesmachine/api/config'
6
+
7
+ module Salesmachine
8
+ class Api
9
+ class Client
10
+ include Salesmachine::Api::Utils
11
+
12
+ # public: Creates a new client
13
+ #
14
+ # attrs - Hash
15
+ # :api_key - String of your project's api_key
16
+ # :max_queue_size - Fixnum of the max calls to remain queued (optional)
17
+ # :on_error - Proc which handles error calls from the API
18
+ def initialize(attrs = {})
19
+ symbolize_keys! attrs
20
+
21
+ @queue = Queue.new
22
+ @api_key = attrs[:api_key]
23
+ @max_queue_size = attrs[:max_queue_size] || Config::Queue::MAX_SIZE
24
+ @options = attrs
25
+ @worker_mutex = Mutex.new
26
+ @worker = Worker.new @queue, @api_key, @options
27
+
28
+ check_api_key!
29
+
30
+ at_exit { @worker_thread && @worker_thread[:should_exit] = true }
31
+ end
32
+
33
+ # public: Synchronously waits until the worker has flushed the queue.
34
+ # Use only for scripts which are not long-running, and will
35
+ # specifically exit
36
+ #
37
+ def flush
38
+ while !@queue.empty? || @worker.is_requesting?
39
+ ensure_worker_running
40
+ sleep(0.1)
41
+ end
42
+ end
43
+
44
+ # public: Tracks an event
45
+ #
46
+ # attrs - Hash
47
+ def track(attrs)
48
+ symbolize_keys! attrs
49
+ check_contact_id! attrs
50
+
51
+ event = attrs[:event]
52
+ params = attrs[:params] || {}
53
+ created_at = attrs[:created_at] || Time.new
54
+
55
+ check_timestamp! created_at
56
+
57
+ if event.nil? || event.empty?
58
+ fail ArgumentError, 'Must supply event as a non-empty string'
59
+ end
60
+
61
+ fail ArgumentError, 'Params must be a Hash' unless params.is_a? Hash
62
+ isoify_dates! params
63
+
64
+ enqueue(event: event,
65
+ contact_uid: attrs[:contact_uid],
66
+ params: params,
67
+ created_at: datetime_in_iso8601(created_at),
68
+ method: 'event')
69
+ end
70
+
71
+ # public: Send an email
72
+ #
73
+ # attrs - Hash
74
+ def email(attrs)
75
+ symbolize_keys! attrs
76
+ check_contact_id! attrs
77
+
78
+ email = attrs[:email]
79
+ params = attrs[:params] || {}
80
+ created_at = attrs[:created_at] || Time.new
81
+
82
+ check_timestamp! created_at
83
+
84
+ if email.nil? || email.empty?
85
+ fail ArgumentError, 'Must supply email template as a non-empty string'
86
+ end
87
+
88
+ fail ArgumentError, 'Params must be a Hash' unless params.is_a? Hash
89
+ isoify_dates! params
90
+
91
+ enqueue(email: email,
92
+ contact_uid: attrs[:contact_uid],
93
+ params: params,
94
+ created_at: datetime_in_iso8601(created_at),
95
+ method: 'email')
96
+ end
97
+
98
+ def contact(attrs)
99
+ symbolize_keys! attrs
100
+ check_contact_id! attrs
101
+
102
+ params = attrs[:params] || {}
103
+ created_at = attrs[:created_at] || Time.new
104
+
105
+ check_timestamp! created_at
106
+
107
+ fail ArgumentError, 'Must supply params as a hash' unless params.is_a? Hash
108
+ isoify_dates! params
109
+
110
+ enqueue(contact_uid: attrs[:contact_uid],
111
+ params: params,
112
+ created_at: datetime_in_iso8601(created_at),
113
+ method: 'contact')
114
+ end
115
+
116
+ def account(attrs)
117
+ symbolize_keys! attrs
118
+ fail ArgumentError, 'Must supply a contact_uid' unless attrs[:account_uid]
119
+
120
+ account_uid = attrs[:account_uid]
121
+ params = attrs[:params] || {}
122
+ created_at = attrs[:created_at] || Time.new
123
+
124
+ fail ArgumentError, 'Params must be a hash' unless params.is_a? Hash
125
+ isoify_dates! params
126
+
127
+ check_timestamp! created_at
128
+
129
+ enqueue(account_uid: account_uid,
130
+ params: params,
131
+ created_at: datetime_in_iso8601(created_at),
132
+ method: 'account')
133
+ end
134
+
135
+ def pageview(attrs)
136
+ symbolize_keys! attrs
137
+ check_contact_id! attrs
138
+
139
+ params = attrs[:params] || {}
140
+ created_at = attrs[:created_at] || Time.new
141
+
142
+ fail ArgumentError, '.params must be a hash' unless params.is_a? Hash
143
+ isoify_dates! params
144
+
145
+ check_timestamp! created_at
146
+
147
+ enqueue(contact_uid: attrs[:contact_uid],
148
+ event: 'pageview',
149
+ params: attrs[:params],
150
+ created_at: datetime_in_iso8601(created_at),
151
+ method: 'event')
152
+ end
153
+
154
+ # public: Returns the number of queued messages
155
+ #
156
+ # returns Fixnum of messages in the queue
157
+ def queued_messages
158
+ @queue.length
159
+ end
160
+
161
+ private
162
+
163
+ # private: Enqueues the action.
164
+ #
165
+ # returns Boolean of whether the item was added to the queue.
166
+ def enqueue(action)
167
+ # add our request id for tracing purposes
168
+ action[:messageId] = uid
169
+ unless queue_full = @queue.length >= @max_queue_size
170
+ ensure_worker_running
171
+ @queue << action
172
+ end
173
+ !queue_full
174
+ end
175
+
176
+ # private: Ensures that a string is non-empty
177
+ #
178
+ # obj - String|Number that must be non-blank
179
+ # name - Name of the validated value
180
+ #
181
+ def check_presence!(obj, name)
182
+ if obj.nil? || (obj.is_a?(String) && obj.empty?)
183
+ fail ArgumentError, "#{name} must be given"
184
+ end
185
+ end
186
+
187
+ # private: Adds contextual information to the call
188
+ #
189
+ # context - Hash of call context
190
+ def add_context(context)
191
+ context[:library] = { name: 'salesmachine-ruby', version: Salesmachine::Api::VERSION.to_s }
192
+ end
193
+
194
+ # private: Checks that the api_key is properly initialized
195
+ def check_api_key!
196
+ fail ArgumentError, 'Api key must be initialized' if @api_key.nil?
197
+ end
198
+
199
+ # private: Checks the timstamp option to make sure it is a Time.
200
+ def check_timestamp!(timestamp)
201
+ fail ArgumentError, 'Timestamp must be a Time' unless timestamp.is_a? Time
202
+ end
203
+
204
+ def check_contact_id!(attrs)
205
+ fail ArgumentError, 'Must supply a contact_uid' unless attrs[:contact_uid]
206
+ end
207
+
208
+ def ensure_worker_running
209
+ return if worker_running?
210
+ @worker_mutex.synchronize do
211
+ return if worker_running?
212
+ @worker_thread = Thread.new do
213
+ @worker.run
214
+ end
215
+ end
216
+ end
217
+
218
+ def worker_running?
219
+ @worker_thread && @worker_thread.alive?
220
+ end
221
+ end
222
+ end
223
+ end
@@ -0,0 +1,20 @@
1
+ module Salesmachine
2
+ class Api
3
+ module Config
4
+ module Request
5
+ HOST = 'api.salesmachine.io'
6
+ PORT = 443
7
+ PATH = '/v1/batch'
8
+ SSL = true
9
+ HEADERS = { :accept => 'application/json' }
10
+ RETRIES = 4
11
+ BACKOFF = 30.0
12
+ end
13
+
14
+ module Queue
15
+ BATCH_SIZE = 100
16
+ MAX_SIZE = 10000
17
+ end
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,33 @@
1
+ require 'logger'
2
+
3
+ module Salesmachine
4
+ class Api
5
+ module Logging
6
+ class << self
7
+ def logger
8
+ @logger ||= if defined?(Rails)
9
+ Rails.logger
10
+ else
11
+ logger = Logger.new STDOUT
12
+ logger.progname = 'Salesmachine::Api'
13
+ logger
14
+ end
15
+ end
16
+
17
+ attr_writer :logger
18
+ end
19
+
20
+ def self.included(base)
21
+ class << base
22
+ def logger
23
+ Logging.logger
24
+ end
25
+ end
26
+ end
27
+
28
+ def logger
29
+ Logging.logger
30
+ end
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,90 @@
1
+ require 'salesmachine/api/config'
2
+ require 'salesmachine/api/utils'
3
+ require 'salesmachine/api/response'
4
+ require 'salesmachine/api/logging'
5
+ require 'net/http'
6
+ require 'net/https'
7
+ require 'json'
8
+
9
+ module Salesmachine
10
+ class Api
11
+ class Request
12
+ include Salesmachine::Api::Config::Request
13
+ include Salesmachine::Api::Utils
14
+ include Salesmachine::Api::Logging
15
+
16
+ # public: Creates a new request object to send analytics batch
17
+ #
18
+ def initialize(options = {})
19
+ options[:host] ||= HOST
20
+ options[:port] ||= PORT
21
+ # ||= not working on boolean ;-)
22
+ options[:ssl] = SSL if options[:ssl].nil?
23
+
24
+ options[:headers] ||= HEADERS
25
+ @path = options[:path] || PATH
26
+ @retries = options[:retries] || RETRIES
27
+ @backoff = options[:backoff] || BACKOFF
28
+ http = Net::HTTP.new(options[:host], options[:port])
29
+ http.use_ssl = options[:ssl]
30
+ http.verify_mode = OpenSSL::SSL::VERIFY_NONE
31
+ http.read_timeout = 8
32
+ http.open_timeout = 4
33
+
34
+ @http = http
35
+ end
36
+
37
+ # public: Posts the write key and batch of messages to the API.
38
+ #
39
+ # returns - Response of the status and error if it exists
40
+ def post(api_key, batch)
41
+ status = nil
42
+ error = nil
43
+ remaining_retries = @retries
44
+ backoff = @backoff
45
+ headers = { 'Content-Type' => 'application/json', 'accept' => 'application/json' }
46
+ begin
47
+ # payload = JSON.generate :api_token=>api_key, :encode=>"base64", :data=>batch
48
+ payload = batch.to_json
49
+
50
+ request = Net::HTTP::Post.new(@path, headers)
51
+ request.basic_auth api_key, api_key
52
+
53
+ if self.class.stub
54
+ status = 200
55
+ error = nil
56
+ logger.debug "stubbed request to #{@path}: write key = #{api_key}, payload = #{payload}"
57
+ else
58
+ res = @http.request(request, payload)
59
+
60
+ status = res.code.to_i
61
+ unless status == 200 || status == 201
62
+ body = JSON.parse(res.body)
63
+ error = body['error']
64
+ end
65
+ end
66
+ rescue Exception => e
67
+ unless (remaining_retries -= 1).zero?
68
+ sleep(backoff)
69
+ retry
70
+ end
71
+
72
+ logger.error e.message
73
+ e.backtrace.each { |line| logger.error line }
74
+ status = -1
75
+ error = "Connection error: #{e}"
76
+ end
77
+
78
+ Response.new status, error
79
+ end
80
+
81
+ class << self
82
+ attr_accessor :stub
83
+
84
+ def stub
85
+ @stub || ENV['STUB']
86
+ end
87
+ end
88
+ end
89
+ end
90
+ end
@@ -0,0 +1,15 @@
1
+ module Salesmachine
2
+ class Api
3
+ class Response
4
+ attr_reader :status, :error
5
+
6
+ # public: Simple class to wrap responses from the API
7
+ #
8
+ #
9
+ def initialize(status = 200, error = nil)
10
+ @status = status
11
+ @error = error
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,88 @@
1
+ require 'securerandom'
2
+
3
+ module Salesmachine
4
+ class Api
5
+ module Utils
6
+ extend self
7
+
8
+ # public: Return a new hash with keys converted from strings to symbols
9
+ #
10
+ def symbolize_keys(hash)
11
+ hash.inject({}) { |memo, (k, v)| memo[k.to_sym] = v; memo }
12
+ end
13
+
14
+ # public: Convert hash keys from strings to symbols in place
15
+ #
16
+ def symbolize_keys!(hash)
17
+ hash.replace symbolize_keys hash
18
+ end
19
+
20
+ # public: Return a new hash with keys as strings
21
+ #
22
+ def stringify_keys(hash)
23
+ hash.inject({}) { |memo, (k, v)| memo[k.to_s] = v; memo }
24
+ end
25
+
26
+ # public: Returns a new hash with all the date values in the into iso8601
27
+ # strings
28
+ #
29
+ def isoify_dates(hash)
30
+ hash.inject({}) do |memo, (k, v)|
31
+ memo[k] = datetime_in_iso8601(v)
32
+ memo
33
+ end
34
+ end
35
+
36
+ # public: Converts all the date values in the into iso8601 strings in place
37
+ #
38
+ def isoify_dates!(hash)
39
+ hash.replace isoify_dates hash
40
+ end
41
+
42
+ # public: Returns a uid string
43
+ #
44
+ def uid
45
+ arr = SecureRandom.random_bytes(16).unpack('NnnnnN')
46
+ arr[2] = (arr[2] & 0x0fff) | 0x4000
47
+ arr[3] = (arr[3] & 0x3fff) | 0x8000
48
+ '%08x-%04x-%04x-%04x-%04x%08x' % arr
49
+ end
50
+
51
+ def datetime_in_iso8601(datetime)
52
+ case datetime
53
+ when Time
54
+ time_in_iso8601 datetime
55
+ when DateTime
56
+ time_in_iso8601 datetime.to_time
57
+ when Date
58
+ date_in_iso8601 datetime
59
+ else
60
+ datetime
61
+ end
62
+ end
63
+
64
+ def time_in_iso8601(time, fraction_digits = 3)
65
+ fraction = if fraction_digits > 0
66
+ ('.%06i' % time.usec)[0, fraction_digits + 1]
67
+ end
68
+
69
+ "#{time.strftime('%Y-%m-%dT%H:%M:%S')}#{fraction}#{formatted_offset(time, true, 'Z')}"
70
+ end
71
+
72
+ def date_in_iso8601(date)
73
+ date.strftime('%F')
74
+ end
75
+
76
+ def formatted_offset(time, colon = true, alternate_utc_string = nil)
77
+ time.utc? && alternate_utc_string || seconds_to_utc_offset(time.utc_offset, colon)
78
+ end
79
+
80
+ def seconds_to_utc_offset(seconds, colon = true)
81
+ (colon ? UTC_OFFSET_WITH_COLON : UTC_OFFSET_WITHOUT_COLON) % [(seconds < 0 ? '-' : '+'), (seconds.abs / 3600), ((seconds.abs % 3600) / 60)]
82
+ end
83
+
84
+ UTC_OFFSET_WITH_COLON = '%s%02d:%02d'
85
+ UTC_OFFSET_WITHOUT_COLON = UTC_OFFSET_WITH_COLON.sub(':', '')
86
+ end
87
+ end
88
+ end
@@ -0,0 +1,5 @@
1
+ module Salesmachine
2
+ class Api
3
+ VERSION = "1.0.0"
4
+ end
5
+ end
@@ -0,0 +1,59 @@
1
+ require 'salesmachine/api/utils'
2
+ require 'salesmachine/api/config'
3
+ require 'salesmachine/api/request'
4
+
5
+ module Salesmachine
6
+ class Api
7
+ class Worker
8
+ include Salesmachine::Api::Utils
9
+ include Salesmachine::Api::Config
10
+
11
+ # public: Creates a new worker
12
+ #
13
+ # The worker continuously takes messages off the queue
14
+ # and makes requests to the salesmachine.io api
15
+ #
16
+ # queue - Queue synchronized between client and worker
17
+ # api_key - String of the application's Api key
18
+ # options - Hash of worker options
19
+ # batch_size - Fixnum of how many items to send in a batch
20
+ # on_error - Proc of what to do on an error
21
+ #
22
+ def initialize(queue, api_key, options = {})
23
+ symbolize_keys! options
24
+ @queue = queue
25
+ @api_key = api_key
26
+ @batch_size = options[:batch_size] || Queue::BATCH_SIZE
27
+ @on_error = options[:on_error] || proc { |_status, _error| }
28
+ @batch = []
29
+ @lock = Mutex.new
30
+ @options = options
31
+ end
32
+
33
+ # public: Continuously runs the loop to check for new events
34
+ #
35
+ def run
36
+ until Thread.current[:should_exit]
37
+ return if @queue.empty?
38
+
39
+ @lock.synchronize do
40
+ until @batch.length >= @batch_size || @queue.empty?
41
+ @batch << @queue.pop
42
+ end
43
+ end
44
+ res = Request.new(@options).post @api_key, @batch
45
+
46
+ @lock.synchronize { @batch.clear }
47
+
48
+ @on_error.call res.status, res.error unless res.status == 200
49
+ end
50
+ end
51
+
52
+ # public: Check whether we have outstanding requests.
53
+ #
54
+ def is_requesting?
55
+ @lock.synchronize { !@batch.empty? }
56
+ end
57
+ end
58
+ end
59
+ end
@@ -0,0 +1,37 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'salesmachine/api/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "salesmachine-ruby"
8
+ spec.version = Salesmachine::Api::VERSION
9
+ spec.authors = ["Salesmachine"]
10
+ spec.email = ["team@salesmachine.io"]
11
+
12
+ spec.summary = %q{Salesmachine.io ruby client}
13
+ spec.description = %q{Ruby client for the next gen Salesmachine.io CRM.}
14
+ spec.homepage = "http://salesmachine.io"
15
+ spec.license = "MIT"
16
+
17
+ # Prevent pushing this gem to RubyGems.org by setting 'allowed_push_host', or
18
+ # delete this section to allow pushing this gem to any host.
19
+ if spec.respond_to?(:metadata)
20
+ spec.metadata['allowed_push_host'] = "https://rubygems.org"
21
+ else
22
+ raise "RubyGems 2.0 or newer is required to protect against public gem pushes."
23
+ end
24
+
25
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
26
+ spec.bindir = "exe"
27
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
28
+ spec.require_paths = ["lib"]
29
+
30
+ spec.add_development_dependency "bundler", "~> 1.10"
31
+ spec.add_development_dependency 'rake', '~> 10.3'
32
+ spec.add_development_dependency 'wrong', '~> 0.0'
33
+ spec.add_development_dependency 'rspec', '~> 2.0'
34
+ spec.add_development_dependency 'tzinfo', '1.2.1'
35
+ spec.add_development_dependency 'activesupport', '>= 3.0.0', '<4.0.0'
36
+
37
+ end
metadata ADDED
@@ -0,0 +1,156 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: salesmachine-ruby
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Salesmachine
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2015-09-01 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.10'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.10'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.3'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.3'
41
+ - !ruby/object:Gem::Dependency
42
+ name: wrong
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '0.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '0.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rspec
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '2.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '2.0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: tzinfo
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - '='
74
+ - !ruby/object:Gem::Version
75
+ version: 1.2.1
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - '='
81
+ - !ruby/object:Gem::Version
82
+ version: 1.2.1
83
+ - !ruby/object:Gem::Dependency
84
+ name: activesupport
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: 3.0.0
90
+ - - "<"
91
+ - !ruby/object:Gem::Version
92
+ version: 4.0.0
93
+ type: :development
94
+ prerelease: false
95
+ version_requirements: !ruby/object:Gem::Requirement
96
+ requirements:
97
+ - - ">="
98
+ - !ruby/object:Gem::Version
99
+ version: 3.0.0
100
+ - - "<"
101
+ - !ruby/object:Gem::Version
102
+ version: 4.0.0
103
+ description: Ruby client for the next gen Salesmachine.io CRM.
104
+ email:
105
+ - team@salesmachine.io
106
+ executables: []
107
+ extensions: []
108
+ extra_rdoc_files: []
109
+ files:
110
+ - ".gitignore"
111
+ - ".rspec"
112
+ - CODE_OF_CONDUCT.md
113
+ - Gemfile
114
+ - LICENSE
115
+ - LICENSE.txt
116
+ - README.md
117
+ - Rakefile
118
+ - bin/console
119
+ - bin/setup
120
+ - lib/salesmachine.rb
121
+ - lib/salesmachine/api.rb
122
+ - lib/salesmachine/api/client.rb
123
+ - lib/salesmachine/api/config.rb
124
+ - lib/salesmachine/api/logging.rb
125
+ - lib/salesmachine/api/request.rb
126
+ - lib/salesmachine/api/response.rb
127
+ - lib/salesmachine/api/utils.rb
128
+ - lib/salesmachine/api/version.rb
129
+ - lib/salesmachine/api/worker.rb
130
+ - salesmachine-ruby.gemspec
131
+ homepage: http://salesmachine.io
132
+ licenses:
133
+ - MIT
134
+ metadata:
135
+ allowed_push_host: https://rubygems.org
136
+ post_install_message:
137
+ rdoc_options: []
138
+ require_paths:
139
+ - lib
140
+ required_ruby_version: !ruby/object:Gem::Requirement
141
+ requirements:
142
+ - - ">="
143
+ - !ruby/object:Gem::Version
144
+ version: '0'
145
+ required_rubygems_version: !ruby/object:Gem::Requirement
146
+ requirements:
147
+ - - ">="
148
+ - !ruby/object:Gem::Version
149
+ version: '0'
150
+ requirements: []
151
+ rubyforge_project:
152
+ rubygems_version: 2.4.6
153
+ signing_key:
154
+ specification_version: 4
155
+ summary: Salesmachine.io ruby client
156
+ test_files: []