Code Monkey home page Code Monkey logo

mixpanel-ruby's Introduction

mixpanel-ruby: The official Mixpanel Ruby library

mixpanel-ruby is a library for tracking events and sending Mixpanel profile updates to Mixpanel from your ruby applications.

Installation

gem install mixpanel-ruby

Getting Started

require 'mixpanel-ruby'

tracker = Mixpanel::Tracker.new(YOUR_MIXPANEL_TOKEN)

# Track an event on behalf of user "User1"
tracker.track('User1', 'A Mixpanel Event')

# Send an update to User1's profile
tracker.people.set('User1', {
    '$first_name' => 'David',
    '$last_name' => 'Bowie',
    'Best Album' => 'The Rise and Fall of Ziggy Stardust and the Spiders from Mars'
})

The primary class you will use to track events is Mixpanel::Tracker. An instance of Mixpanel::Tracker is enough to send events directly to Mixpanel, and get you integrated right away.

Additional Information

For more information please visit:

The official Mixpanel gem is built with simplicity and broad applicability in mind, but there are also third party Ruby libraries that can work with the library to provide useful features in common situations, and support different development points of view.

In particular, for Rails apps, the following projects are currently actively maintained:

Changes

2.2.2

  • Add Group Analytics support with Mixpanel::Groups

2.2.1

  • Fix buffer clearing on partially successful writes in BufferedConsumer.

2.2.0

  • Add Mixpanel::ErrorHandler to simplify custom error handling.

  • Modify Mixpanel::People#fix_property_dates to handle ActiveSupport::TimeWithZone.

  • Increase open and ssl timeouts from 2s to 10s.

  • Fix Doc inconsistancy: always pass token on Mixpanel::tracker.new.

2.1.0

  • Add Mixpanel::Tracker#generate_tracking_url, which generates pixel tracking urls.

  • Rescue JSONErrors in the consumer and raise Mixpanel::ServerError in Mixpanel::Consumer#send!.

  • Make it clear how to import events with custom timestamp.

  • Update dependancies in gemspec

2.0.1

  • Add Deprecated version of Mixpanel::BufferedConsumer#send

2.0.0

  • Raise mixpanel server and connection errors in Mixpanel::Consumer.

  • All public methods in Mixpanel::Event, Mixpanel::People, and subsequently Mixpanel::Tracker rescue Mixpanel errors and return false in the case of an error, return true otherwise

  • Deprecate Mixpanel::Consumer#send, replace with Mixpanel::Consumer#send!

  • Require ruby version minimum of 2.0.0

1.4.0

  • Allow unset to unset multiple properties

1.3.0

  • Added Consumer#request method, demo with Faraday integration

1.2.0

  • All objects with a “strftime” method will be formatted as dates in people updates.

1.1.0

  • The default consumer now sends requests (and expects responses) in verbose, JSON mode, which may improve error reporting.

1.0.2

  • Allow ip and optional_params arguments to be accepted by all Mixpanel::People methods (except #destroy_user)

1.0.1

  • Compatibility with earlier versions of ruby. Library development will continue to target 1.9, so later versions may not be compatible with Ruby 1.8, but we love patches!

1.0.0

  • tracker#import added

  • Change to internal tracking message format. Messages written by earlier versions of the library will not work with 1.0.0 consumer classes.

  • alias bugfixed

  • Fixes to tests to allow for different timezones

  • Support for optional/experimental people api properties in people calls

mixpanel-ruby's People

Contributors

andrewpurcell avatar austinpray-mixpanel avatar cade avatar davidstosik avatar douwem avatar dstosik avatar etiennedepaulis avatar exviva avatar gdiaz avatar greysteil avatar jaredmixpanel avatar joeatwork avatar jsuarezb avatar marcferna avatar miguelmadero avatar mixpanelsteve avatar pius avatar romanbsd avatar rossdakin avatar rubymerchant avatar shaicoleman avatar tdumitrescu avatar thomasklemm avatar timonv avatar zelnox avatar zyskowsk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mixpanel-ruby's Issues

Consumer#send() overrides Object#send()

This is absolutely not what is intended. This method should be renamed, even though this will be a backward breaking change and require a major version increment of the library.

Problems with JRuby support

Earlier i found this issue #73 which should be fixed by #74. I dig dipper and found that server return empty bodies because of JRuby bug jruby/jruby#1216 (comment). This bug happens only when you run it in experimental Ruby 2.0 support mode (i had to turn it on because this gem require ruby version >= 2 and fails to install on default JRuby).

So currently its impossible to make it work with Net:HTTP and latest stable JRuby. Why there were added such script requirement of ruby version >= 2?

Expose Meaningful Errors To Caller

When you call Mixpanel::Tracker#track or Mixpanel::Tracker#import, all errors are caught and not sent to the calling application (https://github.com/mixpanel/mixpanel-ruby/blob/master/lib/mixpanel-ruby/events.rb#L125). I would like to suggest a change where the calling application receives the error along with what event/properties were attempted to send.

Without further information to why the call failed, it is impossible to debug the system. Was it an improper token? Bad data sent? Was mixpanel just momentarily unavailable? The MixpanelError should be exposed to the calling application so that the application can decide if it needs to resend the data or log an error.

Timezones break the tests

The following rake spec failure is reported from a user:

# /spec/mixpanel-ruby/people_spec.rb:63
       expected: [[:profile_update, {"data"=>{"$token"=>"TEST TOKEN", "$distinct_id"=>"TEST ID", "$time"=>76695784000, "$add"=>{"Albums Released"=>1}}}]]
            got: [[:profile_update, {"data"=>{"$token"=>"TEST TOKEN", "$time"=>76692184000, "$distinct_id"=>"TEST ID", "$add"=>{"Albums Released"=>1}}}]]

Failures like these make it harder for people to contribute to the library, which is bad.

Fine tune default timeouts

Current timeouts are too short for users in some parts of the world, however, we don't want to introduce too much unexpected variability into batch jobs. We should fine-tune our default timeouts to contain most (but not all) real-world timings during normal server operation.

See #61 for some discussion

delete_user not working

delete_user (https://github.com/mixpanel/mixpanel-ruby/blob/master/lib/mixpanel-ruby/people.rb#L205-L213) always returns false for me, and never deletes the user.

From my code:

    tracker = Mixpanel::Tracker.new(token)
    result = tracker.people.delete_user(distinct_id)
    puts "deleting #{distinct_id}: #{result}"

Sample output:

deleting 9029: false
deleting 9040: false
deleting 15236: false
deleting 3472: false
deleting 146559c382c61d-044b5fc87-32203e1e-2c600-146559c382d60: false
deleting 2367: false
deleting 3499: false

Set HTTP connection timeouts

I have been affected by the downtime tonight in a particularly bad way. We send some events in background jobs. These jobs started to hang, and so our queues backed up.

The underlying cause seems to be that Net::HTTP has a default open_timeout of nil (i.e. unlimited). Due to the downtime, the requests to Mixpanel's API were simply hanging.

I think the default in Net::HTTP is pretty bad. But to shield Mixpanel users from problems caused by API downtime I suggest that this library could/should set a default timeout so that requests don't hang indefinitely.

Next Release?

Hi,
I'm wondering when the next release will be that will include my commit to ignore alias property?
Thanks,
Eric

Error when using alias: 'Could not write to Mixpanel'

I'm receiving the following error when attempting to use .alias:

Mixpanel::ConnectionError in Devise::InvitationsController#create

In my scenario when a user signs up for our newsletter we add them to Mixpanel via email:

tracker = Mixpanel::Tracker.new(ENV["MIXPANEL_API_KEY"])
tracker.people.set(self.email, {
      '$created' => self.created_at,
      '$email' => self.email,
      'Email Id' => self.id
})

Once they are converted to a User (via invitation) I'm attempting to alias the user id:

tracker = Mixpanel::Tracker.new(ENV["MIXPANEL_API_KEY"])
tracker.alias(self.id, self.email) if Email.where(email: self.email).exists?

I've tried a number of different scenarios is there a known issue with Mixpanel::Tracker#alias in the gem?

When mixpanel servers are down, the gems does work so the apps using the gem doesn't work

So few minutes ago, I guess mixpanel had an outage.

My guess is that the call made by the gem did not succeed and the gem does not handle failure like it should. It caused some part of our app to crash.

Here is a list of error we had:

SSL_connect SYSCALL returned=5 errno=0 state=unknown state`
Net::ReadTimeout
Could not write to Mixpanel, server responded with 500 returning: '<html> <head><title>500 Internal Server Error</title></head> <body bgcolor="white"> <center><h1>500 Internal Server Error</h1></center> <hr><center>nginx/1.1.19</center> </body> </html> '

I think the correct behaviour would be to handle/make it fail silently?

README.md is outdated

Hello,

Trying to see what's the difference between 1.4.0 and 1.7.0, I searched for a changelog, and only found an incomplete one in the readme file (it only goes to 1.4.0).
I'd like to know what are the changes since 1.4.0, and see if there's anything I need to do to get 1.7.0 to work properly on my existing installation that's running 1.4.0.

Thanks,
David

Tracking calls should swallow consumer exceptions in default events and people classes

Throwing an exception in Consumer.send on failure is probably the right thing to do, but the exception should not be propegated through the standard people and events tracking calls - clients rarely want to halt on tracking failures, and requiring try: catch: boilerplate around all calls noises up code, and is a bit wasteful if those calls might later send delegate to buffering or out-of-process consumers. Tracking calls should return falsy values if they detect immediate failures, and folks who want more universal error handling for consumers should use block constructors to catch and deal with the consumer exceptions.

3.0.0: Consider removing ip parameter from api

Remove the ip parameter from event and people methods. Update docs to illustrate how to use optional_params in people methods, as well as how to pass ip in event methods by passing ip in the properties.

Preserving request context in delayed jobs?

In zevarito/mixpanel, the Tracker object takes an optional env argument which can be used to preserve the request context (user-agent, etc.) even if the call to Mixpanel is deferred until it's consumed by some delayed job system like Sidekiq. Is there a way to do this with this new gem?

Mixpanel::People#fix_property_dates breaks date timezones if they are not UTC

Hello,

In the following, the date shown by Mixpanel does not match the date in my database:

tracker.people.set(user.id, { '$created_at' => user.created_at})

My Mixpanel project is set to Asia/Tokyo timezone, and user.created_at produces a Time in the same timezone, but still, the time showed in Mixpanel is offset by 9 hours.
This is because Mixpanel::People#fix_property_dates converts time properties to well-formatted strings, but forgets about the timezone.
There are at least two options to fix this:

  • include the timezone in the date format used in strftime at lib/mixpanel-ruby/people.rb#L253, like this: '%Y-%m-%dT%H:%M:%S%:z' (Mixpanel seems to be accepting this syntax, as my dates are fine if I convert them myself to this format before sending)
  • remove Mixpanel::People#fix_property_dates completely, and leave it to #to_json that, apparently (from a few tests I ran), does a good enough job producing a string that is valid for Mixpanel, and includes timezone. Edit after some research: according to commit 235be50, it is a bad idea to leave it to #to_json, as its behaviour may fluctuate.

Other opinion is welcome, I'll try to provide a patch when I get some.

Thanks,
David

read server certificate B: certificate verify failed

I'm trying to add Mixpanel to our back end and do a call to the people.set endpoint.

My call looks like this:

    res = @tracker.people.set(
        user.id, {
            '$first_name'       => user.first_name,
            '$last_name'        => user.last_name,
            '$email'            => user.email,
            '$phone'            => user.phone,
            '$created'          => user.created_at
        })
    res

In all my testing, res is simply 'false'

I used my debugger to dig into the gem a little bit and I'm finding that there is a connection error exception thrown on line 100 of consumer.rb:

"SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed"

I don't have any trouble making calls to the mixpanel api using javascript, so I think my machine is configured fine, also this is my local machine so my server will have a different environment.

mixpanel breaks cucumber tests

Hi,
i'm using cucumber+capybara to test my app. But after adding mixpanel to my code i've got errors

Mixpanel::ConnectionError at /users =================================== > Could not write to Mixpanel, server responded with 200 returning: '{"status": 0, "error": "distinct_id, missing or empty"}' 

how can i fix it?

Consumer#import always sets time to now instead of user defined

Hi,
I would like to make a script to import old events for a new event I am creating. Unfortunately with how import is implemented it always sets the time when the event occured to when the script is run, not when the event actually happened.

Thanks,
Eric

Filtering bot

Hi there

I noticed that mixpanel-ruby doesn't filter traffic from bot/crawlers. I find it inconsistents with how mixpanel's javascript client is implemented (which filters javascript). Is there any reason to this behaviour?

Thanks in advance for the explanation

Fine-tune requirements so rubygems stops warning

we get the following warnings when we build:

WARNING:  open-ended dependency on rake (>= 0, development) is not recommended
  if rake is semantically versioned, use:
    add_development_dependency 'rake', '~> 0'
WARNING:  pessimistic dependency on rspec (~> 3.0.0, development) may be overly strict
  if rspec is semantically versioned, use:
    add_development_dependency 'rspec', '~> 3.0', '>= 3.0.0'
WARNING:  pessimistic dependency on webmock (~> 1.18.0, development) may be overly strict
  if webmock is semantically versioned, use:
    add_development_dependency 'webmock', '~> 1.18', '>= 1.18.0'
WARNING:  See http://guides.rubygems.org/specification-reference/ for help

People properties are not converted to UTC for TimeWithZone values

When setting a user property with a Rails DateTime attribute, mixpanel is save save the incorrect time in the user profile.

The mixpanel-ruby fix_property_dates method is only converting dates to UTC if the object responds to new_offset and the ActiveSupport::TimeWithZone class does not.

sample code to reproduce the issue:

MY_TOKEN = 'insert token here'
DISTINCT_ID = 'unique people id'
zone = 'Eastern Time (US & Canada)'
tracker = Mixpanel::Tracker.new(MY_TOKEN)

model = MyModel.find(some_id)
time = model.created_at.in_time_zone(zone)
#=> ActiveSupport::TimeWithZone
time.respond_to?(:new_offset)
#=> false

Time.use_zone(zone) do
  # time is being saved in mixpanel using local time instead of UTC
  tracker.people.set(DISTINCT_ID, test_property: time)
end

Add pixel-based event tracking

A good reason to use server side Mixpanel at all is to process and send email messages, which need tracking URLs for their links. Make this a simple process using existing library function.

(See #32 for generate_tracking_url, which should probably be public. Thanks to @pius for the original PQ and idea!)

send event error.

i try to use the gem for server api data analytic,but i didn't trigger it.

I try this:
gem install 'mixpanel-ruby'
require 'mixpanel-ruby'
t = Mixpanel::Tracker.new('MYTOKEN')
t.track(1,'A Mixpanel Event')

it just give me
'=> false'

I didn't see the action data working the panel,please check it.

I don't receive events into my mixpanel

Hi guys

I am from abiquo.

We are trying mixpanel and connecting a ruby app that we have with your SaaS

I should be doing things correctly, because there is no error raised, but I don't see anything in the Panel and still appear the message saying that "it haven't received anything"

This is an example usage

  tracker = Mixpanel::Tracker.new(API_KEYS['mixpanel']['token'])


  tracker.people.set(member.id, {
    'username' => member.username,
    'name' => member.name,
    'mail' => member.mail,
    'enterprise' => member.organization.splitsplit(" - ")[0]
  })


  tracker.track(member.id, 'user_registered')

I have added some logger to see if token is correct, and it is

I need some help

People set with optional param $ignore_time does not work. Last Seen always updated

      tracker.people.set(u.id, {
        '$first_name' => u.first_name,
        '$last_name' => u.last_name,
        '$email' => u.email
      }, optional_params = {
        # For server-side updates, do not update last seen and geolocation
        '$ignore_time' => true,
        '$ip' => '0'
      })

When run, Last Seen is always updated to "less than a minute ago" on Mixpanel. This should not happen per Mixpanel docs. $ip => '0' works correctly, as geolocation properties are not updated from server-side IP address.

As a workaround I'm using Typhoeus against Mixpanel's HTTP API, here is the equivalent request.

      data = Base64.encode64({
        '$token' => ENV['MIXPANEL_API_TOKEN'],
        '$ip' => '0', # Do not update geolocation from server-side
        '$ignore_time' => true, # Do not update Last Seen from server-side
        '$distinct_id' => u.id,
        '$set' => {
          '$first_name' => u.first_name,
          '$last_name' => u.last_name,
          '$email' => u.email
        }
      }.to_json)
      request = Typhoeus::Request.new(
        'https://api.mixpanel.com/engage/',
        method: :get,
        params: { data: data, verbose: 1 }
      )

With this request, $ignore_time is functioning correctly.

How do I manage test env

Hello,

Do you provide a test mode to not send requests to mixpanel when I run my unit tests?

Thx

Tracking with Delayed_job

I've got mixpanel tracking on delayed jobs but it seems like the events aren't being sent properly.

Some controller:
Mixpaneltracking.instance.signup(@user.id)

Mixpanel.rb:
def signup(id)
@mixpanel.track(id, "Sign Up")
end
handle_asynchronously :signup

Coerce BigDecimal to float

BigDecimal values appear to end up in Mixpanel as strings rather than numbers.

While they can manually be coerced into numbers in the Mixpanel UI, it would be nice if the Ruby API delivered them as numbers rather than strings so that step isn't necessary.

500/Mixpanel down errors throw unpredictable exceptions from consumer

Reported by @theonegri in comments of #12 -regardless of the resolution of that issue, the library shouldn't throw exceptions in these circumstances, since we don't know that the relevant callers will still be around.

We still need to decide how to best indicate that an error has occurred, so that callers who care to can retry or log the issue.

people.set unexpectedly updates 'Last Seen'

Last Seen seems to be conflated with profile.updated_at

I'm updating a users' profile via mixpanel-ruby to reflect changes made from an administrative UI (ie. User.disabled = false) that we would like to share with Mixpanel without confusing this with a user event in the Mixpanel People/Explore UI.

Instead of using Last Seen, then, should I explicitly set a Last Page Load timestamp via the JS client which we can use to differentiate JS client updates from ruby client updates?

Events Import API not supported

Thank you for writing this gem. I love the minimalistic design of the lib.

Having said that, do you think events import API belong here? I am in the process of moving to Mixpanel and happy to lend a hand to add import implementation to both Consumer and BufferredConsumer classes.

Randomly thows errors

It happen from time to time, probably because some API issues, but definitely this case not handled:

irb(main):006:0> tracker.track(2, "Viewed people search")
NoMethodError: undefined method `[]' for nil:NilClass
    from /usr/local/bundle/gems/mixpanel-ruby-2.0.1/lib/mixpanel-ruby/consumer.rb:106:in `send!'
    from org/jruby/RubyMethod.java:124:in `call'
    from /usr/local/bundle/gems/mixpanel-ruby-2.0.1/lib/mixpanel-ruby/events.rb:70:in `track'
    from /usr/local/bundle/gems/mixpanel-ruby-2.0.1/lib/mixpanel-ruby/tracker.rb:72:in `track'
    from (irb):6:in `evaluate'
    from org/jruby/RubyKernel.java:1107:in `eval'
    from org/jruby/RubyKernel.java:1507:in `loop'
    from org/jruby/RubyKernel.java:1270:in `catch'
    from org/jruby/RubyKernel.java:1270:in `catch'
    from /opt/jruby/bin/irb:13:in `(root)'

Tests fails due to timezone difference

I have few tests failing indicating possibly due to Timezone difference. for example, in events_spec.rb, we use following:

@time_now = Time.parse('Jun 6 1972, 16:23:04')

On my machine, @time_now gets set in PDT and hence @time_now.to_i doesn't match the hardcoded time 76695784 in the test.

We probably should not hardcode time, and instead just use @time_now.to_i in the test (A commit coming soon)

Mixpanel-ruby v mixpanel gems

I'm jumping on a new project that uses the old mixpanel gem [https://github.com/zevarito/mixpanel]. I'd like to just swap out the old gem for this one in my Gemfile...does anyone know if there will be any issues with this? Any critical changes I'd have to make?

response_body returning as �V*.I,)-V�R0�QPJ-*�/��Jsrj��9

Having an odd issue when sending events. Response comes back and raises the following error -

<Mixpanel::ConnectionError: Could not write to Mixpanel, server responded with 200 returning: '�V*.I,)-V�R0�QPJ-*�/��Jsrj��9'>

Event registers in mixpanel, and works fine...

Any ideas?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.