## Ruby SDK

## Instant insights from any Ruby app

This documentation provides guidance on how to integrate the June SDK with your Ruby application. June SDK is a powerful library for tracking user interactions and events, offering similar functionality to the underlying Segment SDK.

## Getting Started

## Installation

To install the June SDK in your Ruby project:

```sh
gem install june-analytics-ruby
```

## Configuration

First, you'll need to import the SDK into your application. Next, instantiate the client using the write key you've received when you created your June account:

```coffeescript
require 'june/analytics'

Analytics = June::Analytics.new({
  write_key: 'YOUR_WRITE_KEY'
})
```

If you're using Rails, you can create a config/initializers/analytics_ruby.rb file and add the following code:

```coffeescript
require 'june/analytics'

Analytics = June::Analytics.new({
  write_key: 'YOUR_WRITE_KEY',
  on_error: proc { |_status, msg| print msg },
  test: !Rails.env.production?
})
```

Now you can use the analytics instance to track events, identify users, and more.

## API Reference

## Client configuration

The June Ruby SDK configuration process involves setting various options when initializing the `June::Analytics`. These options allow you to fine-tune how the SDK interacts with the June Analytics service.

Here are the primary configuration options that you can set:

| Option           | Type     | Description                                                                                                                                                          | Required |
| ---------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- |
| write_key        | String   | The unique key of your project in the June Analytics service, used to authenticate your application.                                                                  | Yes      |
| batch_size       | Fixnum   | The number of items to send in a batch.                                                                                                                             | No       |
| max_queue_size   | Fixnum   | The maximum number of calls that can remain queued at any given time. This queue holds data before it gets sent to June Analytics service.                         | No       |
| on_error         | Proc     | A Proc that defines what should happen when an error occurs while making a call to the API.                                                                         | No       |
| test             | Boolean  | A boolean flag indicating whether the client is operating in test mode. When this option is set to true, events are not actually sent to the June Analytics API.    | No       |

The options are provided as a hash to the `initialize` method of the `Client` class:

```coffeescript
Analytics = June::Analytics.new({
  write_key: 'YOUR_WRITE_KEY',
  max_queue_size: 1000,
  on_error: proc { |status, error| puts "Error: #{status}, #{error.message}" },
  test: true
})
```

Remember to replace `'YOUR_WRITE_KEY'` with your actual project's write key. The `max_queue_size` and `on_error` options are optional, and you can leave them out if you're happy with the default settings. If you're not testing, you should set the `test` option to `false` or just omit it entirely.

## Tracking Events

To track events, you can use the `track` method:

```coffeescript
Analytics.track({
  user_id: 'USER_ID',
  event: 'Signed In',
  properties: {
    browser: 'chrome'
  }
})
```

Parameters:

| Parameter    | Type     | Description                                                                                                                                                         | Required |
| ------------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- |
| userId       | String   | The ID for this user in your database. Note: At least one of userId or anonymousId must be included in any track call.                                           | Optional |
| anonymousId  | String   | An ID associated with the user when you don’t know who they are.                                                                                            | Optional |
| event        | String   | The name of the event you’re tracking. It is recommended to use human-readable names like 'Song Played' or 'Status Updated'.                                    | Required |
| properties    | Object   | A dictionary of properties for the event. For instance, if the event was 'Product Added', it might have properties like price or product.                       | Optional |
| timestamp    | Date     | A ruby date object representing when the track took place. If the track just happened, leave it out and the server’s time will be used.                          | Optional |
| context      | Object   | A dictionary of extra context to attach to the call.  Context differs from traits because it is not attributes of the user itself.                                | Optional |

## Identifying Users & Setting User Traits

To identify users, you can use the `identify` method:

```coffeescript
Analytics.identify({
  user_id: 'USER_ID',
  traits: {
    email: "test@example.com",
    # Optional
    name: "Joe Bloggs",
    avatar: "https://avatar.com/d78979as8hlsa9088f.png"
    # Add anything else about the user here
  }
})
```

Parameters:

| Parameter    | Type     | Description                                                                                                                                                             | Required |
| ------------ | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- |
| userId       | String   | The ID for this user in your database. Note: At least one of userId or anonymousId must be included in any identify call.                                            | Optional |
| anonymousId  | String   | An ID associated with the user when you don’t know who they are.                                                                                                   | Optional |
| traits       | Object   | A dictionary of traits you know about the user. Things like: email, name, or friends.                                                                                | Optional |
| timestamp    | Date     | A ruby date object representing when the identify took place. If the identify just happened, leave it out as Segment uses the server’s time.                        | Optional |
| context      | Object   | A dictionary of extra context to attach to the call.  Context differs from traits because it is not attributes of the user itself.                                   | Optional |

## Grouping Users

To group users by organization or company, use the `group` method:

```coffeescript
Analytics.group({
  user_id: 'USER_ID',
  group_id: 'GROUP_ID',
  traits: {
    name: "Acme Inc",
    # Optional
    avatar: "https://avatar.com/d78979as8hlsa9088f.png"
    # Add anything else about the company here
  }
})
```

Parameters:

| Parameter    | Type     | Description                                                                                                                                                        | Required |
| ------------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------- |
| userId       | String   | The ID for this user in your database. Note: At least one of userId or anonymousId must be included in any group call.                                          | Optional |
| anonymousId  | String   | An ID associated with the user when you don’t know who they are.                                                                                           | Optional |
| groupId      | String   | The ID of the group.                                                                                                                                           | Required |
| traits       | Object   | A dictionary of traits you know about the group. For a company, they might be things like name, address, or phone.                                              | Optional |
| timestamp    | Date     | A ruby date object representing when the group took place. If the group just happened, leave it out and the server’s time will be used.                        | Optional |
| context      | Object   | A dictionary of extra context to attach to the call. Context differs from traits because it is not attributes of the user itself.                                | Optional |

## Serverless environments

In serverless environments like AWS Lambda, your environment may finish the code execution before June SDK is able to send events to June API.

You can use the `flush` method to send all queued events to June or you can configure the SDK to flush events automatically.

## Flush events manually

```coffeescript
Analytics.flush
```

## Flush events automatically

If you set `batch_size` to `1`, the SDK will flush events automatically after every event.

```coffeescript
Analytics = June::Analytics.new({
  write_key: 'YOUR_WRITE_KEY',
  batch_size: 1,
  on_error: proc { |status, error| puts "Error: #{status}, #{error.message}" },
})
```

## Writing tests

To test that your June integration is working as expected you can use the `test` option. When this option is set to `true`, events are not actually sent to the June Analytics API. Instead, they're added to a test queue. This is useful for debugging and testing.

Your initialization code should include the `test` option:

```coffeescript
Analytics = June::Analytics.new({
  write_key: 'YOUR_WRITE_KEY',
  on_error: proc { |_status, msg| print msg },
  test: !Rails.env.production?
})
```

Then in your spec code you can check that the events are being sent to the test queue:

```coffeescript
# frozen_string_literal: true

require 'rails_helper'

RSpec.describe ::YourClass do
  context 'When your code includes an Analytics.track()' do
    context 'when there is no error' do
      let(:subject) { described_class.run!() }

it 'send event to analytics' do
        subject
        expect(Analytics.test_queue.messages[:all].length).to eq(1)
        expect(Analytics.test_queue.messages[:track].length).to eq(1)
        expect(Analytics.test_queue.messages[:track].first[:event]).to eq('your event name')
      end
    end
  end
end
```

Note: It is recommended to call `reset!` before each test to ensure your test queue is empty. For example, in rspec you may have the following:

```coffeescript
RSpec.configure do |config|
  config.before do
    Analytics.test_queue.reset!
  end
end
```

If you want to see all the methods available in the test queue class check the [June Ruby SDK source code](https://github.com/juneHQ/analytics-ruby/blob/master/lib/june/analytics/test_queue.rb)
