> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mixpanel.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Mixpanel SDKs: Ruby

## Getting Started

The Mixpanel Ruby library is designed to be used for scripting, or in circumstances when a user isn't directly interacting with your application on the web or a mobile device.

The [Full API Reference](http://mixpanel.github.io/mixpanel-ruby), [Library Source Code](https://github.com/mixpanel/mixpanel-ruby), and an [Example Script](https://github.com/mixpanel/mixpanel-ruby/tree/master/demo) is documented in our GitHub repo.

See our [server](/docs/quickstart/connect-your-data?sdk=ruby) quickstart for how to get started with the Ruby SDK.

## Installing the Library

<Warning>For projects with EU or India data residency, you must configure the SDK to use the correct regional endpoint. Events sent to the wrong region will not be ingested. Learn more about [Privacy-Friendly Tracking](/docs/tracking-methods/sdks/ruby#privacy-friendly-tracking).</Warning>

To install the library, call the following in your command line to install the `mixpanel-ruby` gem:

```bash theme={"system"}
# install mixpanel ruby sdk with gem
gem install mixpanel-ruby
```

After the installation, import the gem and create an instance of the `Mixpanel::Tracker` class to start using the library in your code:

```ruby theme={"system"}
# import the mixpanel gem
require 'mixpanel-ruby'

# create an instance of the Mixpanel class
tracker = Mixpanel::Tracker.new("YOUR_PROJECT_TOKEN")
```

## Sending Events

Use [`track()`](http://mixpanel.github.io/mixpanel-ruby/Mixpanel/Events.html#method-i-track) to send an event by providing the distinct\_id, event name, and any event properties. This will trigger a request to the [/track API endpoint](/reference/track-event) to ingest the event into your project.

<Note>
  The [/track endpoint](/reference/track-event) will only validate events with timestamps within the last 5 days of the request. Events with timestamps older than 5 days will not be ingested. See below on best practices for historical imports.
</Note>

**Example Usage**

```ruby theme={"system"}
# create an instance of the Mixpanel class
require 'mixpanel-ruby'
tracker = Mixpanel::Tracker.new("YOUR_PROJECT_TOKEN")

# track "some_event" for distinct_id 12345
# with "plan" event prop
tracker.track('12345', 'some_event', {
    'plan' => 'Premium'
})
```

Mixpanel determines default geolocation data (`$city`, `$region`, `mp_country_code`) using the IP address on the incoming request. As all server-side calls will likely originate from the same IP (that is, the IP of your server), this can have the unintended effect of setting the location of all of your users to the location of your data center. [Learn more about best practices for geolocation.](/docs/tracking-best-practices/geolocation).

### Importing Historical Events

The [`track()`](http://mixpanel.github.io/mixpanel-ruby/Mixpanel/Events.html#method-i-track) function is designed for real-time tracking in a server-side environment and will trigger request to the [/track API endpoint](/reference/track-event), which will validate for events with a time stamp that is within the last 5 days of the request. **Events older than 5 days will not be ingested.**

Use the [`import()`](http://mixpanel.github.io/mixpanel-ruby/Mixpanel/Events.html#method-i-import) function to import events that occurred more than 5 days in the past. The `import()` function is based on the [/import API endpoint](/reference/import-events).

**Example Usage**

```ruby theme={"system"}
# create an instance of the Mixpanel class
require 'mixpanel-ruby'
tracker = Mixpanel::Tracker.new("YOUR_PROJECT_TOKEN")

# track "some_event" for distinct_id 12345
# with "plan" event prop
tracker.import("API_KEY", "12345", "Welcome Email Sent", {
    'Email Template' => 'Pretty Pink Welcome',
    'User Sign-up Cohort' => 'July 2013',
    'time' => 1369353600,
})
```

You can also use the [mp-utils python module](https://github.com/mixpanel/mixpanel-utils) designed for scripting.

## Managing User Identity

Since the Ruby SDK is a server-side library, IDs are not generated by the SDK. Instead, you will need to generate and manage the distinct\_id yourself and include it in your events and profile data.

Learn more about [server-side identity management](/docs/tracking-methods/id-management/identifying-users-simplified#server-side-identity-management).

## Storing User Profiles

Once your users are identified, create [user profiles](/docs/data-structure/user-profiles) by setting profile properties to describe them. Example profile properties include "name", "email", "company", and any other demographic details about the user.

The Ruby SDK provides a few methods for setting profile properties, which will trigger requests to the [/engage API endpoint](/reference/profile-set).

Mixpanel determines default geolocation data (`$city`, `$region`, `mp_country_code`) using the IP address on the incoming request. As all server-side calls will likely originate from the same IP (that is, the IP of your server), this can have the unintended effect of setting the location of all of your users to the location of your data center. [Learn more about best practices for geolocation.](/docs/tracking-best-practices/geolocation).

### Setting Profile Properties

Instances of [`Mixpanel::Tracker`](http://mixpanel.github.io/mixpanel-ruby/Mixpanel/Tracker.html) have a property called `people` that is an instance of [`Mixpanel::People`](http://mixpanel.github.io/mixpanel-ruby/Mixpanel/People.html), which contain methods for managing user profile properties.

Set profile properties on a user profile by calling [`people.set()`](https://mixpanel.github.io/mixpanel-ruby/Mixpanel/People.html#method-i-set).

If a profile property already exists, it will be overwritten with the latest value provided in the method. If a profile property does not exist, it will be added to the profile.

**Example Usage**

```ruby theme={"system"}
# create an instance of the Mixpanel class
require 'mixpanel-ruby'
tracker = Mixpanel::Tracker.new("YOUR_PROJECT_TOKEN")

# create a user profile with name and email props
tracker.people.set('sample_distinct_id', {
    'name'       => 'Sam',
    '$email'     => 'sam@example.com'
}, ip = 0); # do not update geolocation

# update name property from "sam" to "samantha"
tracker.people.set('sample_distinct_id', {
    'name'       => 'Samantha'
}, ip = 0);
```

### Other Types of Profile Updates

There are a few other methods for setting profile properties. See a complete reference of the available methods [here](http://mixpanel.github.io/mixpanel-ruby/Mixpanel/People.html).

A few commonly used people methods are highlighted below:

<Tabs>
  <Tab title="set_once()">
    The [`set_once()`](https://mixpanel.github.io/mixpanel-ruby/Mixpanel/People.html#method-i-set_once) method set profile properties only if they do not exist yet. If it is setting a profile property that already exists, it will be ignored.

    Use this method if you want to set profile properties without the risk of overwriting existing data.

    **Example Usage**

    ```ruby theme={"system"}
    # create an instance of the Mixpanel class
    require 'mixpanel-ruby'
    tracker = Mixpanel::Tracker.new("YOUR_PROJECT_TOKEN")

    # set profile properties for user "1234"
    tracker.people.set('1234', {
    'name'  => 'Sam'
    }, ip = 0);


    # will be ignored since "name" already exists
    tracker.people.set_once('1234', {
    'name'  => 'Samantha'
    }, ip = 0);

    # set "location" user prop since it does not exist
    tracker.people.set_once('1234', {
    'location'  => 'us'
    }, ip = 0);
    ```
  </Tab>

  <Tab title="append()">
    The [`append()`](https://mixpanel.github.io/mixpanel-ruby/Mixpanel/People.html#method-i-append) method append values to a list profile property.

    Use this method to add additional values to an existing list property instead of redefining the entire list.

    **Example Usage**

    ```ruby theme={"system"}
    # create an instance of the Mixpanel class
    require 'mixpanel-ruby'
    tracker = Mixpanel::Tracker.new("YOUR_PROJECT_TOKEN");

    # set profile properties for user "1234"
    tracker.people.set('1234', {
    'name'  => 'Sam',
    'roles' => ['sales','engineer']
    }, ip = 0);


    # add "legal" to "roles"  
    # new role values are ['sales','engineer','legal']
    tracker.people.append("1234", {
    'roles' => 'legal'
    }, ip = 0);

    # .append() allows duplicates
    # new "roles" values are ['sales','engineer','legal', 'legal']
    tracker.people.append("1234", {
    'roles' => 'legal'
    }, ip = 0);
    ```
  </Tab>

  <Tab title="union()">
    The [`union()`](https://mixpanel.github.io/mixpanel-ruby/Mixpanel/People.html#method-i-union) method append new values to a list property, excluding duplicates.

    Use this method to create a list profile property that only contains unique values without duplicates.

    **Example Usage**

    ```ruby theme={"system"}
    # create an instance of the Mixpanel class
    require 'mixpanel-ruby'
    tracker = Mixpanel::Tracker.new("YOUR_PROJECT_TOKEN")

    # set profile properties for user "1234"
    tracker.people.set('1234', {
    'name'  => 'Sam',
    'roles' => ['sales','engineer']
    }, ip = 0);

    # "engineer" ignored since it already exists
    # append "legal" to "roles"
    tracker.people.union("1234", {
    'roles' => ['engineer','legal']
    }, ip = 0);
    ```
  </Tab>

  <Tab title="increment()">
    The [`increment()`](https://mixpanel.github.io/mixpanel-ruby/Mixpanel/People.html#method-i-increment) method increments a numeric property by a whole number.

    Use this method to add to or subtract from your numeric property based on its current value.

    **Example Usage**

    ```ruby theme={"system"}
    # create an instance of the Mixpanel class
    require 'mixpanel-ruby'
    tracker = Mixpanel::Tracker.new("YOUR_PROJECT_TOKEN")

    # set profile properties for user "1234"
    tracker.people.set('1234', {
    'name'  => 'Sam',
    'age' => 25
    }, ip = 0);

    # increment "age" by 2
    tracker.people.increment('1234', {
    'age'  => 2,
    }, ip = 0);

    # use negative number to decrement
    # decrement "age" by 5
    tracker.people.increment('1234', {
    'age'  => -5,
    }, ip = 0);
    ```
  </Tab>
</Tabs>

## Group Analytics

<Note>
  Read more about [Group Analytics](/docs/data-structure/group-analytics) before proceeding. You will need to have the [group key defined in your project settings](/docs/data-structure/group-analytics#group-keys-in-project-settings) first.
</Note>

Mixpanel Group Analytics is a paid add-on that allows behavioral data analysis by selected groups, as opposed to individual users.

A group is identified by the `group_key` and `group_id`.

* `group_key` is the event property that connects event data to a group. (e.g. `company`)
* `group_id` is the identifier for a specific group. (e.g. `mixpanel`,`company_a`,`company_b`, etc.)

### Sending Group Identifiers With Events

[All events must have the group key as an event property in order to be attributed to a group](/docs/data-structure/group-analytics#group-keys-tracked-as-event-properties). Without the group key, an event cannot be attributed to a group.

To send group identifiers with your events, set the `group_key` as an event property with the `group_id` as the value.

**Example Usage**

```ruby theme={"system"}
# track "some_event" with "sample_distinct_id"
# event is attributed to the "mixpanel" company group
Tracker = Mixpanel::Tracker.new("YOUR_PROJECT_TOKEN")
tracker.track("sample_distinct_id", “some_event”, {
  "company" => "mixpanel"
})
```

**Multiple Groups**

[An event can be attributed to multiple groups](/docs/data-structure/group-analytics#attribute-events-to-multiple-groups) by passing in the `group_key` value as a list of multiple `group_id` values.

**Example Usage**

```ruby theme={"system"}
# track "some_event" with a "distinct_id"
# event is attributed to 2 company groups: "mp-us" and "mp-eu"
Tracker = Mixpanel::Tracker.new("YOUR_PROJECT_TOKEN")
tracker.track("sample_distinct_id", “some_event”, {
  "company" => ["mp-us","mp-eu"]
})
```

### Adding Group Identifiers to User Profiles

To connect group information to a user profile, include the `group_key` and `group_id` as a user profile property using the `.people.set()` call.

**Example Usage**

```ruby theme={"system"}
# create an instance of the Mixpanel class
require 'mixpanel-ruby'
tracker = Mixpanel::Tracker.new("YOUR_PROJECT_TOKEN")

# set group key "company" as a user prop
# with group id "mixpanel" as value
tracker.people.set('sample_distinct_id', {
    'name'       => 'Sam',
    'company'     => 'mixpanel'
}, ip = 0);
```

### Setting Group Profile Properties

Create a group profile by setting group properties, similar to a user profile. For example, you may want to describe a company group with properties such as "ARR", "employee\_count", and "subscription".

Instances of [`Mixpanel::Tracker`](http://mixpanel.github.io/mixpanel-ruby/Mixpanel/Tracker.html) have a property called `groups` that is an instance of [`Mixpanel::Groups`](https://mixpanel.github.io/mixpanel-ruby/Mixpanel/Groups.html), which contain methods for managing group profile properties.

To set group profile properties, use the [`groups.set()`](https://mixpanel.github.io/mixpanel-ruby/Mixpanel/Groups.html#method-i-set) method, which will trigger a request to the [/groups API endpoint](/reference/group-set-property).

**Example Usage**

```ruby theme={"system"}
# create group profile for the "mixpanel" company group
# set "Company Type" and "$name" group profile properties
tracker = Mixpanel::Tracker.new(YOUR_MIXPANEL_TOKEN)
tracker.groups.set('company', 'mixpanel', {
  '$name' => 'Mixpanel',
  'Company Type' => 'Analytics',
})
```

### Other Group Profile Methods

See all of the methods under the Groups class [here](http://mixpanel.github.io/mixpanel-ruby/Mixpanel/Groups.html).

A few commonly used group methods are highlighted below:

<Tabs>
  <Tab title="set_once()">
    The [`set_once()`](https://mixpanel.github.io/mixpanel-ruby/Mixpanel/Groups.html#method-i-set_once) method set group profile properties only if they do not exist yet. If it is setting a profile property that already exists, it will be ignored.

    Use this method if you want to set group profile properties without the risk of overwriting existing data.

    **Example Usage**

    ```ruby theme={"system"}
    tracker = Mixpanel::Tracker.new(YOUR_MIXPANEL_TOKEN)

    # set group profile for "mixpanel" company group
    tracker.groups.set('company', 'mixpanel', {
      'name' => 'Mixpanel',
      'employee_count' => 100
    })

    # ignored since "name" is already exists
    tracker.groups.set_once('company', 'mixpanel', {
      'name' => 'mp-us',
    })

    # set "location" group prop since it does not exist
    tracker.groups.set_once('company', 'mixpanel', {
      'location' => 'us',
    })
    ```
  </Tab>

  <Tab title="unset()">
    The [`unset()`](https://mixpanel.github.io/mixpanel-ruby/Mixpanel/Groups.html#method-i-unset) method removes a group property from a group profile.

    Use this method to delete unwanted group profile properties from a specific group profile.

    **Example Usage**

    ```ruby theme={"system"}
    tracker = Mixpanel::Tracker.new(YOUR_MIXPANEL_TOKEN)

    # set group profile for the "mixpanel" company group
    tracker.groups.set('company', 'mixpanel', {
      'name' => 'Mixpanel',
      'employee_count' => 100
    })

    # delete "employee_count" from the group profile
    tracker.groups.unset('company', 'mixpanel', 'employee_count')

    # only "name" remains as a group prop
    ```
  </Tab>

  <Tab title="union()">
    The [`union()`](https://mixpanel.github.io/mixpanel-ruby/Mixpanel/Groups.html#method-i-union) method append new values to a list property, excluding duplicates.

    Use this method to create a list group profile property that only contains unique values without duplicates.

    **Example Usage**

    ```ruby theme={"system"}
    tracker = Mixpanel::Tracker.new(YOUR_MIXPANEL_TOKEN)

    # set group profile for the "mixpanel" company group
    tracker.groups.set('company', 'mixpanel', {
      'name' => 'Mixpanel',
      'features' => ['alert','cohort','reports']
    })

    # add "data pipeline" to "features" prop
    # ignore "alert" since it is a duplicate value
    tracker.groups.union('company','mixpanel', {
        'features' => ['data pipeline','alert']
    })
    ```
  </Tab>

  <Tab title="remove()">
    The [`remove()`](https://mixpanel.github.io/mixpanel-ruby/Mixpanel/Groups.html#method-i-remove) method removes a value from a list-valued group profile property.

    Use this method to remove specific values from a list without affecting all of the other values in the list.

    **Example Usage**

    ```ruby theme={"system"}
    tracker = Mixpanel::Tracker.new(YOUR_MIXPANEL_TOKEN)

    # set group profile for the "mixpanel" company group
    mp.groups.set('company','mixpanel', {
        'name' => 'Mixpanel',
        'features' => ['reports','alerts','cohorts']
    })

    # remove "alerts" from "features"
    # "features" now contain ["reports","cohorts"]
    mixpanel.groups.remove('company','mixpanel', {
        'features' => ['alerts']
    })
    ```
  </Tab>
</Tabs>

## Privacy-Friendly Tracking

You have control over the data you send to Mixpanel. The Ruby SDK have a few configurations to help you protect user data.

Since this is a server-side tracking library where you have control of the servers, your server is responsible for determining whether to send data about a particular user or not.

### EU Data Residency

Route data to Mixpanel's EU servers by using a custom [consumer](http://mixpanel.github.io/mixpanel-ruby/Mixpanel/Consumer.html):

**Example Usage**

```ruby theme={"system"}
require 'mixpanel-ruby'

eu_consumer = Mixpanel::Consumer.new(
    'https://api-eu.mixpanel.com/track', #set track request URL
    'https://api-eu.mixpanel.com/engage', #set profile request URL
    'https://api-eu.mixpanel.com/groups', #set group request URL
)

# initialize Mixpanel with your custom consumer
tracker = Mixpanel::Tracker.new(YOUR_PROJECT_TOKEN) do |type, message|
    eu_consumer.send!(type, message)
end
```

### India Data Residency

Route data to Mixpanel's India servers by using a custom [consumer](http://mixpanel.github.io/mixpanel-ruby/Mixpanel/Consumer.html):

**Example Usage**

```ruby theme={"system"}
require 'mixpanel-ruby'

in_consumer = Mixpanel::Consumer.new(
    'https://api-in.mixpanel.com/track', #set track request URL
    'https://api-in.mixpanel.com/engage', #set profile request URL
    'https://api-in.mixpanel.com/groups', #set group request URL
)

# initialize Mixpanel with your custom consumer
tracker = Mixpanel::Tracker.new(YOUR_PROJECT_TOKEN) do |type, message|
    in_consumer.send!(type, message)
end
```

### Disable Geolocation

The Ruby SDK parse the request IP address to generate geolocation properties for events and profiles. You may want to disable them to prevent the unintentional setting of your data's geolocation to the location of your server that is sending the request, or to prevent geolocation data from being tracked entirely.

To disable geolocation, set the `ip` of your events and profile updates to `0`.

**Example Usage**

```ruby theme={"system"}
require 'mixpanel-ruby'
tracker = Mixpanel::Tracker.new(YOUR_MIXPANEL_TOKEN)

# track "some_event" without geolocation parsing
tracker.track('sample_distinct_id', 'some_event', {
    'plan' => 'Premium'
}, ip=0)

# set age property without geolocation parsing
tracker.people.set('1234', {
    'age'  => -5,
    }, ip = 0);
```

## Release History

[See all releases.](https://github.com/mixpanel/mixpanel-ruby/releases)
