ankane / ahoy

Simple, powerful, first-party analytics for Rails
MIT License
4.2k stars 377 forks source link

Ahoy with stimulus reflex #467

Closed leoplct closed 3 years ago

leoplct commented 3 years ago

I haven't found the information in the doc about how to use Ahoy with a StimulusReflex controller. ahoy is not defined. How can I use it?

class ItemReflex < ApplicationReflex
  before_reflex do
    @item = Item.find(element.dataset[:id])
  end
  after_reflex do 
    ahoy.track 'Item Updated', @item
  end
end

undefined local variable or method `ahoy'

ankane commented 3 years ago

Hey @leoplct, you should be able to add an ahoy method to ApplicationReflex.

class ApplicationReflex < StimulusReflex::Reflex
  def ahoy
    @ahoy ||= Ahoy::Tracker.new(request: request)
  end
end
leoplct commented 3 years ago

Thanks, it's better now.

Do you know how to get the current_user (devise) too?

Must supply either user_id or anonymous_id

ankane commented 3 years ago

If you use master, you can now do:

Ahoy.user_method = lambda do |controller, request|
  controller.try(:current_user) || request.env["warden"].user
end

(place in config/initializers/ahoy.rb)

ankane commented 3 years ago

Cleaning up issues

markfortyau commented 5 months ago

This worked for me:

class ApplicationReflex < StimulusReflex::Reflex
  delegate :current_user, to: :connection
  after_reflex :track_action

  protected

    def ahoy
      @ahoy ||= Ahoy::Tracker.new(user: current_user)
    end

    def track_action
      ahoy.track "Ran reflex action", reflex_name: self.class.name, reflex_params: params.to_unsafe_h
    end
end