mixpanel-ruby-with-pixel-tracking 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 1d4ba4e0efa7356ed86c7d5ea079836a1c22dfb5
4
+ data.tar.gz: 80a6454f9dc22b5602199458cae0b527d841a5ee
5
+ SHA512:
6
+ metadata.gz: 3ec9803cccf0dc2ef3c022ed8c4fbd7b3e6245a348a64035aa40b6e88416cb39263499d55d1d33ce9ccd2daf4be9e50f42b4981c84e9b0e8464d91065c33b94e
7
+ data.tar.gz: 20cf182a055aa6f34675672df0c6cf320efd50d1f43e709d5d2269322c788378118d3afae35f20cbcb413d1bb987bcf2c32ab1dfbeebdedc890699742b7b4221
@@ -0,0 +1,4 @@
1
+ *~
2
+ Gemfile.lock
3
+ html
4
+ mixpanel-ruby*.gem
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --color
2
+ --format progress
data/Gemfile ADDED
@@ -0,0 +1,2 @@
1
+ source 'http://rubygems.org'
2
+ gemspec
data/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+ Copyright 2012 Mixpanel, Inc.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this work except in compliance with the License.
5
+ You may obtain a copy of the License below, or at:
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
14
+
15
+ Apache License
16
+ Version 2.0, January 2004
17
+ http://www.apache.org/licenses/
18
+
19
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
20
+
21
+ 1. Definitions.
22
+
23
+ "License" shall mean the terms and conditions for use, reproduction,
24
+ and distribution as defined by Sections 1 through 9 of this document.
25
+
26
+ "Licensor" shall mean the copyright owner or entity authorized by
27
+ the copyright owner that is granting the License.
28
+
29
+ "Legal Entity" shall mean the union of the acting entity and all
30
+ other entities that control, are controlled by, or are under common
31
+ control with that entity. For the purposes of this definition,
32
+ "control" means (i) the power, direct or indirect, to cause the
33
+ direction or management of such entity, whether by contract or
34
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
35
+ outstanding shares, or (iii) beneficial ownership of such entity.
36
+
37
+ "You" (or "Your") shall mean an individual or Legal Entity
38
+ exercising permissions granted by this License.
39
+
40
+ "Source" form shall mean the preferred form for making modifications,
41
+ including but not limited to software source code, documentation
42
+ source, and configuration files.
43
+
44
+ "Object" form shall mean any form resulting from mechanical
45
+ transformation or translation of a Source form, including but
46
+ not limited to compiled object code, generated documentation,
47
+ and conversions to other media types.
48
+
49
+ "Work" shall mean the work of authorship, whether in Source or
50
+ Object form, made available under the License, as indicated by a
51
+ copyright notice that is included in or attached to the work
52
+ (an example is provided in the Appendix below).
53
+
54
+ "Derivative Works" shall mean any work, whether in Source or Object
55
+ form, that is based on (or derived from) the Work and for which the
56
+ editorial revisions, annotations, elaborations, or other modifications
57
+ represent, as a whole, an original work of authorship. For the purposes
58
+ of this License, Derivative Works shall not include works that remain
59
+ separable from, or merely link (or bind by name) to the interfaces of,
60
+ the Work and Derivative Works thereof.
61
+
62
+ "Contribution" shall mean any work of authorship, including
63
+ the original version of the Work and any modifications or additions
64
+ to that Work or Derivative Works thereof, that is intentionally
65
+ submitted to Licensor for inclusion in the Work by the copyright owner
66
+ or by an individual or Legal Entity authorized to submit on behalf of
67
+ the copyright owner. For the purposes of this definition, "submitted"
68
+ means any form of electronic, verbal, or written communication sent
69
+ to the Licensor or its representatives, including but not limited to
70
+ communication on electronic mailing lists, source code control systems,
71
+ and issue tracking systems that are managed by, or on behalf of, the
72
+ Licensor for the purpose of discussing and improving the Work, but
73
+ excluding communication that is conspicuously marked or otherwise
74
+ designated in writing by the copyright owner as "Not a Contribution."
75
+
76
+ "Contributor" shall mean Licensor and any individual or Legal Entity
77
+ on behalf of whom a Contribution has been received by Licensor and
78
+ subsequently incorporated within the Work.
79
+
80
+ 2. Grant of Copyright License. Subject to the terms and conditions of
81
+ this License, each Contributor hereby grants to You a perpetual,
82
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
83
+ copyright license to reproduce, prepare Derivative Works of,
84
+ publicly display, publicly perform, sublicense, and distribute the
85
+ Work and such Derivative Works in Source or Object form.
86
+
87
+ 3. Grant of Patent License. Subject to the terms and conditions of
88
+ this License, each Contributor hereby grants to You a perpetual,
89
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
90
+ (except as stated in this section) patent license to make, have made,
91
+ use, offer to sell, sell, import, and otherwise transfer the Work,
92
+ where such license applies only to those patent claims licensable
93
+ by such Contributor that are necessarily infringed by their
94
+ Contribution(s) alone or by combination of their Contribution(s)
95
+ with the Work to which such Contribution(s) was submitted. If You
96
+ institute patent litigation against any entity (including a
97
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
98
+ or a Contribution incorporated within the Work constitutes direct
99
+ or contributory patent infringement, then any patent licenses
100
+ granted to You under this License for that Work shall terminate
101
+ as of the date such litigation is filed.
102
+
103
+ 4. Redistribution. You may reproduce and distribute copies of the
104
+ Work or Derivative Works thereof in any medium, with or without
105
+ modifications, and in Source or Object form, provided that You
106
+ meet the following conditions:
107
+
108
+ (a) You must give any other recipients of the Work or
109
+ Derivative Works a copy of this License; and
110
+
111
+ (b) You must cause any modified files to carry prominent notices
112
+ stating that You changed the files; and
113
+
114
+ (c) You must retain, in the Source form of any Derivative Works
115
+ that You distribute, all copyright, patent, trademark, and
116
+ attribution notices from the Source form of the Work,
117
+ excluding those notices that do not pertain to any part of
118
+ the Derivative Works; and
119
+
120
+ (d) If the Work includes a "NOTICE" text file as part of its
121
+ distribution, then any Derivative Works that You distribute must
122
+ include a readable copy of the attribution notices contained
123
+ within such NOTICE file, excluding those notices that do not
124
+ pertain to any part of the Derivative Works, in at least one
125
+ of the following places: within a NOTICE text file distributed
126
+ as part of the Derivative Works; within the Source form or
127
+ documentation, if provided along with the Derivative Works; or,
128
+ within a display generated by the Derivative Works, if and
129
+ wherever such third-party notices normally appear. The contents
130
+ of the NOTICE file are for informational purposes only and
131
+ do not modify the License. You may add Your own attribution
132
+ notices within Derivative Works that You distribute, alongside
133
+ or as an addendum to the NOTICE text from the Work, provided
134
+ that such additional attribution notices cannot be construed
135
+ as modifying the License.
136
+
137
+ You may add Your own copyright statement to Your modifications and
138
+ may provide additional or different license terms and conditions
139
+ for use, reproduction, or distribution of Your modifications, or
140
+ for any such Derivative Works as a whole, provided Your use,
141
+ reproduction, and distribution of the Work otherwise complies with
142
+ the conditions stated in this License.
143
+
144
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
145
+ any Contribution intentionally submitted for inclusion in the Work
146
+ by You to the Licensor shall be under the terms and conditions of
147
+ this License, without any additional terms or conditions.
148
+ Notwithstanding the above, nothing herein shall supersede or modify
149
+ the terms of any separate license agreement you may have executed
150
+ with Licensor regarding such Contributions.
151
+
152
+ 6. Trademarks. This License does not grant permission to use the trade
153
+ names, trademarks, service marks, or product names of the Licensor,
154
+ except as required for reasonable and customary use in describing the
155
+ origin of the Work and reproducing the content of the NOTICE file.
156
+
157
+ 7. Disclaimer of Warranty. Unless required by applicable law or
158
+ agreed to in writing, Licensor provides the Work (and each
159
+ Contributor provides its Contributions) on an "AS IS" BASIS,
160
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
161
+ implied, including, without limitation, any warranties or conditions
162
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
163
+ PARTICULAR PURPOSE. You are solely responsible for determining the
164
+ appropriateness of using or redistributing the Work and assume any
165
+ risks associated with Your exercise of permissions under this License.
166
+
167
+ 8. Limitation of Liability. In no event and under no legal theory,
168
+ whether in tort (including negligence), contract, or otherwise,
169
+ unless required by applicable law (such as deliberate and grossly
170
+ negligent acts) or agreed to in writing, shall any Contributor be
171
+ liable to You for damages, including any direct, indirect, special,
172
+ incidental, or consequential damages of any character arising as a
173
+ result of this License or out of the use or inability to use the
174
+ Work (including but not limited to damages for loss of goodwill,
175
+ work stoppage, computer failure or malfunction, or any and all
176
+ other commercial damages or losses), even if such Contributor
177
+ has been advised of the possibility of such damages.
178
+
179
+ 9. Accepting Warranty or Additional Liability. While redistributing
180
+ the Work or Derivative Works thereof, You may choose to offer,
181
+ and charge a fee for, acceptance of support, warranty, indemnity,
182
+ or other liability obligations and/or rights consistent with this
183
+ License. However, in accepting such obligations, You may act only
184
+ on Your own behalf and on Your sole responsibility, not on behalf
185
+ of any other Contributor, and only if You agree to indemnify,
186
+ defend, and hold each Contributor harmless for any liability
187
+ incurred by, or claims asserted against, such Contributor by reason
188
+ of your accepting any such warranty or additional liability.
189
+
190
+ END OF TERMS AND CONDITIONS
@@ -0,0 +1,13 @@
1
+ require 'rspec/core/rake_task'
2
+ require 'rdoc/task'
3
+
4
+ RSpec::Core::RakeTask.new(:spec) do |spec|
5
+ spec.pattern = 'spec/**/*_spec.rb'
6
+ end
7
+
8
+ Rake::RDocTask.new do |rd|
9
+ rd.main = "Readme.rdoc"
10
+ rd.rdoc_files.include("Readme.rdoc", "lib/**/*.rb")
11
+ end
12
+
13
+ task :default => :spec
@@ -0,0 +1,76 @@
1
+ = mixpanel-ruby: The official Mixpanel Ruby library
2
+
3
+ mixpanel-ruby is a library for tracking events and sending \Mixpanel profile
4
+ updates to \Mixpanel from your ruby applications.
5
+
6
+ == Installation
7
+
8
+ gem install mixpanel-ruby
9
+
10
+ == Getting Started
11
+
12
+ require 'mixpanel-ruby'
13
+
14
+ tracker = Mixpanel::Tracker.new(YOUR_TOKEN)
15
+
16
+ # Track an event on behalf of user "User1"
17
+ tracker.track('User1', 'A Mixpanel Event')
18
+
19
+ # Send an update to User1's profile
20
+ tracker.people.set('User1', {
21
+ '$first_name' => 'David',
22
+ '$last_name' => 'Bowie',
23
+ 'Best Album' => 'The Rise and Fall of Ziggy Stardust and the Spiders from Mars'
24
+ })
25
+
26
+ The primary class you will use to track events is Mixpanel::Tracker. An instance of
27
+ Mixpanel::Tracker is enough to send events directly to \Mixpanel, and get you integrated
28
+ right away.
29
+
30
+ == Additional Information
31
+
32
+ For more information please visit:
33
+
34
+ * Our Ruby API Integration page[https://mixpanel.com/help/reference/ruby#introduction]
35
+ * The usage demo[https://github.com/mixpanel/mixpanel-ruby/tree/master/demo]
36
+ * The documentation[http://mixpanel.github.io/mixpanel-ruby/]
37
+
38
+ The official Mixpanel gem is built with simplicity and broad applicability in
39
+ mind, but there are also third party Ruby libraries that can work with the library
40
+ to provide useful features in common situations. One in particular is
41
+ MetaEvents[https://github.com/swiftype/meta_events], a third party gem
42
+ which provides support for client-side tracking in Rails applications,
43
+ super-properties-like persistent properties, and a DSL for defining your events.
44
+
45
+ == Changes
46
+
47
+ == 1.4.0
48
+ * Allow unset to unset multiple properties
49
+
50
+ == 1.3.0
51
+ * Added Consumer#request method, demo with Faraday integration
52
+
53
+ == 1.2.0
54
+ * All objects with a "strftime" method will be formatted as dates in
55
+ people updates.
56
+
57
+ == 1.1.0
58
+ * The default consumer now sends requests (and expects responses) in
59
+ verbose, JSON mode, which may improve error reporting.
60
+
61
+ === 1.0.2
62
+ * Allow ip and optional_params arguments to be accepted by all
63
+ Mixpanel::People methods (except #destroy_user)
64
+
65
+ === 1.0.1
66
+ * Compatibility with earlier versions of ruby. Library development will continue
67
+ to target 1.9, so later versions may not be compatible with Ruby 1.8, but we
68
+ love patches!
69
+
70
+ === 1.0.0
71
+ * tracker#import added
72
+ * Change to internal tracking message format. Messages written
73
+ by earlier versions of the library will not work with 1.0.0 consumer classes.
74
+ * alias bugfixed
75
+ * Fixes to tests to allow for different timezones
76
+ * Support for optional/experimental people api properties in people calls
@@ -0,0 +1,40 @@
1
+ require 'mixpanel-ruby'
2
+ require 'faraday'
3
+
4
+ # The Mixpanel library's default consumer will use the standard
5
+ # Net::HTTP library to communicate with servers, but you can extend
6
+ # your consumers to use other libraries. This example sends data using
7
+ # the Faraday library (so you'll need that library available to run it)
8
+
9
+ class FaradayConsumer < Mixpanel::Consumer
10
+ def request(endpoint, form_data)
11
+ conn = ::Faraday.new(endpoint)
12
+ response = conn.post(nil, form_data)
13
+ [response.status, response.body]
14
+ end
15
+ end
16
+
17
+ if __FILE__ == $0
18
+ # Replace this with the token from your project settings
19
+ DEMO_TOKEN = '072f77c15bd04a5d0044d3d76ced7fea'
20
+ faraday_consumer = FaradayConsumer.new
21
+
22
+ faraday_tracker = Mixpanel::Tracker.new(DEMO_TOKEN) do |type, message|
23
+ faraday_consumer.send(type, message)
24
+ end
25
+ faraday_tracker.track('ID', 'Event tracked through Faraday')
26
+
27
+ # It's also easy to delegate from a BufferedConsumer to your custom
28
+ # consumer.
29
+
30
+ buffered_faraday_consumer = Mixpanel::BufferedConsumer.new do |type, message|
31
+ faraday_consumer.send(type, message)
32
+ end
33
+
34
+ buffered_faraday_tracker = Mixpanel::Tracker.new(DEMO_TOKEN) do |type, message|
35
+ buffered_faraday_consumer.send(type, message)
36
+ end
37
+
38
+ buffered_faraday_tracker.track('ID', 'Event tracked (buffered) through faraday')
39
+ buffered_faraday_consumer.flush
40
+ end
@@ -0,0 +1,71 @@
1
+ require 'mixpanel-ruby'
2
+ require 'thread'
3
+ require 'json'
4
+ require 'securerandom'
5
+
6
+ # As your application scales, it's likely you'll want to
7
+ # to detect events in one place and send them somewhere
8
+ # else. For example, you might write the events to a queue
9
+ # to be consumed by another process.
10
+ #
11
+ # This demo shows how you might do things, using
12
+ # the block constructor in Mixpanel to enqueue events,
13
+ # and a MixpanelBufferedConsumer to send them to
14
+ # Mixpanel
15
+
16
+ # Mixpanel uses the Net::HTTP library, which by default
17
+ # will not verify remote SSL certificates. In your app,
18
+ # you'll need to call Mixpanel.config_http with the path
19
+ # to your Certificate authority resources, or the library
20
+ # won't verify the remote certificate identity.
21
+ Mixpanel.config_http do |http|
22
+ http.ca_path = '/etc/ssl/certs'
23
+ http.ca_file = "/etc/ssl/certs/ca-certificates.crt"
24
+ http.use_ssl = true
25
+ http.verify_mode = OpenSSL::SSL::VERIFY_PEER
26
+ end
27
+
28
+ class OutOfProcessExample
29
+ class << self
30
+ def run(token, distinct_id)
31
+ open('|-', 'w+') do |subprocess|
32
+ if subprocess
33
+ # This is the tracking process. Once we configure
34
+ # The tracker to write to our subprocess, we can quickly
35
+ # call #track without delaying our other work.
36
+ mixpanel_tracker = Mixpanel::Tracker.new(token) do |*message|
37
+ subprocess.write(message.to_json + "\n")
38
+ end
39
+
40
+ 100.times do |i|
41
+ event = 'Tick'
42
+ mixpanel_tracker.track(distinct_id, event, {'Tick Number' => i})
43
+ puts "tick #{i}"
44
+ end
45
+
46
+ else
47
+ # This is the consumer process. In your applications, code
48
+ # like this may end up in queue consumers or in a separate
49
+ # thread.
50
+ mixpanel_consumer = Mixpanel::BufferedConsumer.new
51
+ begin
52
+ $stdin.each_line do |line|
53
+ message = JSON.load(line)
54
+ type, content = message
55
+ mixpanel_consumer.send(type, content)
56
+ end
57
+ ensure
58
+ mixpanel_consumer.flush
59
+ end
60
+ end
61
+ end
62
+ end # run
63
+ end
64
+ end
65
+
66
+ if __FILE__ == $0
67
+ # Replace this with the token from your project settings
68
+ DEMO_TOKEN = '072f77c15bd04a5d0044d3d76ced7fea'
69
+ run_id = SecureRandom.base64
70
+ OutOfProcessExample.run(DEMO_TOKEN, run_id)
71
+ end
@@ -0,0 +1,8 @@
1
+ require 'mixpanel-ruby'
2
+
3
+ if __FILE__ == $0
4
+ # Replace this with the token from your project settings
5
+ DEMO_TOKEN = '072f77c15bd04a5d0044d3d76ced7fea'
6
+ mixpanel_tracker = Mixpanel::Tracker.new(DEMO_TOKEN)
7
+ mixpanel_tracker.track('ID', 'Script run')
8
+ end
@@ -0,0 +1,3 @@
1
+ require 'mixpanel-ruby/consumer.rb'
2
+ require 'mixpanel-ruby/tracker.rb'
3
+ require 'mixpanel-ruby/version.rb'
@@ -0,0 +1,240 @@
1
+ require 'base64'
2
+ require 'net/https'
3
+ require 'json'
4
+
5
+ module Mixpanel
6
+ class ConnectionError < IOError
7
+ end
8
+
9
+ @@init_http = nil
10
+
11
+ # This method exists for backwards compatibility. The preferred
12
+ # way to customize or configure the HTTP library of a consumer
13
+ # is to override Consumer#request.
14
+ #
15
+ # Ruby's default SSL does not verify the server certificate.
16
+ # To verify a certificate, or install a proxy, pass a block
17
+ # to Mixpanel.config_http that configures the Net::HTTP object.
18
+ # For example, if running in Ubuntu Linux, you can run
19
+ #
20
+ # Mixpanel.config_http do |http|
21
+ # http.ca_path = '/etc/ssl/certs'
22
+ # http.ca_file = '/etc/ssl/certs/ca-certificates.crt'
23
+ # http.verify_mode = OpenSSL::SSL::VERIFY_PEER
24
+ # end
25
+ #
26
+ # \Mixpanel Consumer and BufferedConsumer will call your block
27
+ # to configure their connections
28
+ def self.config_http(&block)
29
+ @@init_http = block
30
+ end
31
+
32
+ # A Consumer recieves messages from a Mixpanel::Tracker, and
33
+ # sends them elsewhere- probably to Mixpanel's analytics services,
34
+ # but can also enqueue them for later processing, log them to a
35
+ # file, or do whatever else you might find useful.
36
+ #
37
+ # You can provide your own consumer to your Mixpanel::Trackers,
38
+ # either by passing in an argument with a #send method when you construct
39
+ # the tracker, or just passing a block to Mixpanel::Tracker.new
40
+ #
41
+ # tracker = Mixpanel::Tracker.new(MY_TOKEN) do |type, message|
42
+ # # type will be one of :event, :profile_update or :import
43
+ # @kestrel.set(ANALYTICS_QUEUE, [type, message].to_json)
44
+ # end
45
+ #
46
+ # You can also instantiate the library consumers yourself, and use
47
+ # them wherever you would like. For example, the working that
48
+ # consumes the above queue might work like this:
49
+ #
50
+ # mixpanel = Mixpanel::Consumer
51
+ # while true
52
+ # message_json = @kestrel.get(ANALYTICS_QUEUE)
53
+ # mixpanel.send(*JSON.load(message_json))
54
+ # end
55
+ #
56
+ # Mixpanel::Consumer is the default consumer. It sends each message,
57
+ # as the message is recieved, directly to Mixpanel.
58
+ class Consumer
59
+
60
+ # Create a Mixpanel::Consumer. If you provide endpoint arguments,
61
+ # they will be used instead of the default Mixpanel endpoints.
62
+ # This can be useful for proxying, debugging, or if you prefer
63
+ # not to use SSL for your events.
64
+ def initialize(events_endpoint=nil, update_endpoint=nil, import_endpoint=nil)
65
+ @events_endpoint = events_endpoint || 'https://api.mixpanel.com/track'
66
+ @update_endpoint = update_endpoint || 'https://api.mixpanel.com/engage'
67
+ @import_endpoint = import_endpoint || 'https://api.mixpanel.com/import'
68
+ end
69
+
70
+ # Send the given string message to Mixpanel. Type should be
71
+ # one of :event, :profile_update or :import, which will determine the endpoint.
72
+ #
73
+ # Mixpanel::Consumer#send sends messages to Mixpanel immediately on
74
+ # each call. To reduce the overall bandwidth you use when communicating
75
+ # with Mixpanel, you can also use Mixpanel::BufferedConsumer
76
+ def send(type, message, as_pixel = false)
77
+ type = type.to_sym
78
+ endpoint = {
79
+ :event => @events_endpoint,
80
+ :profile_update => @update_endpoint,
81
+ :import => @import_endpoint
82
+ }[type]
83
+
84
+ decoded_message = JSON.load(message)
85
+ api_key = decoded_message["api_key"]
86
+ data = Base64.encode64(decoded_message["data"].to_json).gsub("\n", '')
87
+
88
+ form_data = {"data" => data, "verbose" => 1}
89
+ form_data.merge!("api_key" => api_key) if api_key
90
+
91
+ if as_pixel
92
+ form_data.merge!("img" => 1)
93
+ return generate_tracking_url(endpoint, form_data)
94
+ end
95
+
96
+ response_code, response_body = request(endpoint, form_data)
97
+
98
+ succeeded = nil
99
+ if response_code.to_i == 200
100
+ result = JSON.load(response_body) rescue {}
101
+ succeeded = result['status'] == 1
102
+ end
103
+
104
+ if ! succeeded
105
+ raise ConnectionError.new("Could not write to Mixpanel, server responded with #{response_code} returning: '#{response_body}'")
106
+ end
107
+ end
108
+
109
+ # Request takes an endpoint HTTP or HTTPS url, and a Hash of data
110
+ # to post to that url. It should return a pair of
111
+ #
112
+ # [response code, response body]
113
+ #
114
+ # as the result of the response. Response code should be nil if
115
+ # the request never receives a response for some reason.
116
+ def request(endpoint, form_data)
117
+ uri = URI(endpoint)
118
+ request = Net::HTTP::Post.new(uri.request_uri)
119
+ request.set_form_data(form_data)
120
+
121
+ client = Net::HTTP.new(uri.host, uri.port)
122
+ client.use_ssl = true
123
+ Mixpanel.with_http(client)
124
+
125
+ response = client.request(request)
126
+ [response.code, response.body]
127
+ end
128
+
129
+
130
+
131
+ # Generate_tracking_url takes an endpoint HTTP or HTTPS url, and a Hash of data
132
+ # to post to that url. It should return a string for the tracking url:
133
+ #
134
+ # pixel_tracking_url
135
+
136
+ def generate_tracking_url(endpoint, form_data)
137
+ uri = URI(endpoint)
138
+ request = Net::HTTP::Get.new(uri.request_uri)
139
+ request.set_form_data(form_data)
140
+ "#{endpoint}?#{request.body}"
141
+ end
142
+ end
143
+
144
+ # BufferedConsumer buffers messages in memory, and sends messages as
145
+ # a batch. This can improve performance, but calls to #send may
146
+ # still block if the buffer is full. If you use this consumer, you
147
+ # should call #flush when your application exits or the messages
148
+ # remaining in the buffer will not be sent.
149
+ #
150
+ # To use a BufferedConsumer directly with a Mixpanel::Tracker,
151
+ # instantiate your Tracker like this
152
+ #
153
+ # buffered_consumer = Mixpanel::BufferedConsumer.new
154
+ # begin
155
+ # buffered_tracker = Mixpanel::Tracker.new(YOUR_TOKEN) do |type, message|
156
+ # buffered_consumer.send(type, message)
157
+ # end
158
+ # # Do some tracking here
159
+ # ...
160
+ # ensure
161
+ # buffered_consumer.flush
162
+ # end
163
+ #
164
+ class BufferedConsumer
165
+ MAX_LENGTH = 50
166
+
167
+ # Create a Mixpanel::BufferedConsumer. If you provide endpoint arguments,
168
+ # they will be used instead of the default Mixpanel endpoints.
169
+ # This can be useful for proxying, debugging, or if you prefer
170
+ # not to use SSL for your events.
171
+ #
172
+ # You can also change the preferred buffer size before the
173
+ # consumer automatically sends its buffered events. The Mixpanel
174
+ # endpoints have a limit of 50 events per HTTP request, but
175
+ # you can lower the limit if your individual events are very large.
176
+ #
177
+ # By default, BufferedConsumer will use a standard Mixpanel
178
+ # consumer to send the events once the buffer is full (or on calls
179
+ # to #flush), but you can override this behavior by passing a
180
+ # block to the constructor, in the same way you might pass a block
181
+ # to the Mixpanel::Tracker constructor. If a block is passed to
182
+ # the constructor, the *_endpoint constructor arguments are
183
+ # ignored.
184
+ def initialize(events_endpoint=nil, update_endpoint=nil, import_endpoint=nil, max_buffer_length=MAX_LENGTH, &block)
185
+ @max_length = [max_buffer_length, MAX_LENGTH].min
186
+ if block
187
+ @sink = block
188
+ else
189
+ consumer = Consumer.new(events_endpoint, update_endpoint, import_endpoint)
190
+ @sink = consumer.method(:send)
191
+ end
192
+ @buffers = {
193
+ :event => [],
194
+ :profile_update => [],
195
+ }
196
+ end
197
+
198
+ # Stores a message for Mixpanel in memory. When the buffer
199
+ # hits a maximum length, the consumer will flush automatically.
200
+ # Flushes are synchronous when they occur.
201
+ #
202
+ # Currently, only :event and :profile_update messages are buffered,
203
+ # :import messages will be send immediately on call.
204
+ def send(type, message)
205
+ type = type.to_sym
206
+ if @buffers.has_key? type
207
+ @buffers[type] << message
208
+ if @buffers[type].length >= @max_length
209
+ flush_type(type)
210
+ end
211
+ else
212
+ @sink.call(type, message)
213
+ end
214
+ end
215
+
216
+ # Pushes all remaining messages in the buffer to Mixpanel.
217
+ # You should call #flush before your application exits or
218
+ # messages may not be sent.
219
+ def flush
220
+ @buffers.keys.each { |k| flush_type(k) }
221
+ end
222
+
223
+ private
224
+
225
+ def flush_type(type)
226
+ @buffers[type].each_slice(@max_length) do |chunk|
227
+ data = chunk.map {|message| JSON.load(message)['data'] }
228
+ @sink.call(type, {'data' => data}.to_json)
229
+ end
230
+ @buffers[type] = []
231
+ end
232
+ end
233
+
234
+ private
235
+ def self.with_http(http)
236
+ if @@init_http
237
+ @@init_http.call(http)
238
+ end
239
+ end
240
+ end