Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to profile a rails controller that returns a json response with rack-mini-profiler?

I am using rack-mini-profiler in my rails 3.2 project.

In gemfile:

gem 'rack-mini-profiler'

Everything works great. But my application is mostly a set of json endpoints. So while it is very useful to be to able to inspect the performance of html pages, I would like to also be able to see the performance of controllers that return json.

Example of my controller:

class UsersController < BaseController
  def json_method
    # you don't see the mini profiler ui for this controller
    render json: { users: [:foo, :bar]}
  end
end

If I go to localhost:3000/users/json_method, I see my json response but not the profiler ui.

like image 829
Benjamin Crouzier Avatar asked May 14 '14 14:05

Benjamin Crouzier


4 Answers

In development, by default, the rack-mini-profiler gem collects the previous JSON call and presents it in the menu accessible from the HTML page. No code change required.

So, make your JSON request, then hit any other HTML page and it will be available in the list. We use this to great effect. If your Rails app is a JSON API service only, make sure you have a 404.html in your public folder at least, then hit something like:

http://localhost/404.html
like image 94
hlascelles Avatar answered Oct 21 '22 07:10

hlascelles


if rack mini profiler can’t display the results, it will collect them until it can on the next HTML page. So, the solution that I am using is to:

make the JSON request and then hit an HTML page of my choice. The results will appear, along with the most recent HTML profile.

http://tech.eshaiju.in/blog/2016/02/25/profile-api-endpoints-using-rack-mini-profiler/

like image 22
eshaiju Avatar answered Oct 21 '22 08:10

eshaiju


In the second tab, you can visit this URL /rack-mini-profiler/requests Where you can see the last request log

like image 7
Sanjay Prajapati Avatar answered Oct 21 '22 07:10

Sanjay Prajapati


As a first solution, you can just set the format to html, and render inside the html page:

The controller:

class UsersController < BaseController
  def json_method
    @users_json { users: [:foo, :bar]}
    render 'index', formats: ['html']
  end
end

And in app/views/users/index.html.erb:

Users:<br/>
<%= @json.inspect %>

I don't care so much about my json result, now I have the profiling ui.

A solution where I have the profiling ui without changing my controller would be much better.

like image 1
Benjamin Crouzier Avatar answered Oct 21 '22 07:10

Benjamin Crouzier