Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Help: PostHog Client available from all controllers/models #17

Closed
leoplct opened this issue Jul 5, 2022 · 1 comment
Closed

Help: PostHog Client available from all controllers/models #17

leoplct opened this issue Jul 5, 2022 · 1 comment

Comments

@leoplct
Copy link

leoplct commented Jul 5, 2022

I have added posthog client initialization in config/initializers/posthog.rb

config/initializers/posthog.rb

posthog = PostHog::Client.new({
    api_key: "phc_XXXX",
    api_host: "https://app.posthog.com", # You can remove this line if you're using app.posthog.com
    on_error: Proc.new { |status, msg| print msg }
})

How can I have the posthog variable available from all controllers/models in my projects? Maybe using a singleton?
It needs to be memory efficient and avoid instantiating multiple times the same PostHog::client object.

app/controllers/test_controller.rb

class ApiController < ApplicationController
  def test
   posthog.capture({
            distinct_id: 1,
            event: 'test',
            properties: {}
  end
end
@leoplct leoplct changed the title PostHog Client is not a class/module Help: PostHog Client available from all controllers/models Jul 5, 2022
@leoplct
Copy link
Author

leoplct commented Jul 5, 2022

SOLVED.
I suggest to add this in the documentation.

config/initializers/posthog.rb

::PostHogApi = PostHog::Client.new({
    api_key: "phc_XXXX",
    api_host: "https://app.posthog.com", # You can remove this line if you're using app.posthog.com
    on_error: Proc.new { |status, msg| print msg }
})

services/dev/analytics.rb

class Dev::Analytics
    def self.track(user_id, event, properties={})
        ::PostHogApi.capture({
            distinct_id: user_id,
            event: event,
            properties: properties
        })
    end
end

controller.rb

Dev::Analytics.track(current_user.id, 'event_name', {})

@leoplct leoplct closed this as completed Jul 5, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant