Sha256: ae64beca80d517ec0e4faaae5c2454f5c96cd8669ba9f854ad468f1b60ddde21

Contents?: true

Size: 1.41 KB

Versions: 2

Compression:

Stored size: 1.41 KB

Contents

# frozen_string_literal: true

module RailsMiniProfiler
  class RequestContext
    attr_reader :request

    attr_accessor :response, :profiled_request, :traces, :flamegraph

    def initialize(request)
      @request = request
      @env = request.env
      @saved = false
      @complete = false
    end

    def user_id
      @user_id ||= User.current_user
    end

    def authorized?
      @authorized ||= User.get(@env).present?
    end

    def complete_profiling!
      profiled_request.user_id = user_id
      profiled_request.request = @request
      profiled_request.response = @response
      total_time = traces.find { |trace| trace.name == 'rails_mini_profiler.total_time' }
      profiled_request.total_time = total_time
      @complete = true
    end

    def save_results!
      ActiveRecord::Base.transaction do
        profiled_request.flamegraph = Flamegraph.new(data: flamegraph) if flamegraph.present?
        profiled_request.save
        insert_traces unless traces.empty?
      end
      @saved = true
    end

    def complete?
      @complete
    end

    def saved?
      @saved
    end

    private

    def insert_traces
      return if traces.empty?

      timestamp = Time.zone.now
      inserts = traces.map do |trace|
        { rmp_profiled_request_id: profiled_request.id, **trace.to_h, created_at: timestamp, updated_at: timestamp }
      end
      RailsMiniProfiler::Trace.insert_all(inserts)
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
rails_mini_profiler-0.1.1 lib/rails_mini_profiler/request_context.rb
rails_mini_profiler-0.1.0 lib/rails_mini_profiler/request_context.rb