Class: Ahoy::EventsController

Inherits:
BaseController show all
Defined in:
app/controllers/ahoy/events_controller.rb

Instance Method Summary collapse

Instance Method Details

#createObject



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'app/controllers/ahoy/events_controller.rb', line 3

def create
  events =
    if params[:name]
      # legacy API and AMP
      [request.params]
    elsif params[:events]
      request.params[:events]
    else
      data =
        if params[:events_json]
          request.params[:events_json]
        else
          request.body.read
        end
      begin
        ActiveSupport::JSON.decode(data)
      rescue ActiveSupport::JSON.parse_error
        # TODO change to nil in Ahoy 6
        []
      end
    end

  max_events_per_request = Ahoy.max_events_per_request

  # check before creating any events
  unless events.is_a?(Array) && events.first(max_events_per_request).all? { |v| v.is_a?(Hash) }
    logger.info "[ahoy] Invalid parameters"
    # :unprocessable_entity is probably more correct
    # but keep consistent with missing parameters for now
    render plain: "Invalid parameters\n", status: :bad_request
    return
  end

  events.first(max_events_per_request).each do |event|
    time = Time.zone.parse(event["time"]) rescue nil

    # timestamp is deprecated
    time ||= Time.zone.at(event["time"].to_f) rescue nil

    options = {
      id: event["id"],
      time: time
    }
    ahoy.track event["name"], event["properties"], options
  end
  render json: {}
end