moorara
moorara

Reputation: 4226

How to add a custom route, controller, and action in Ruby on Rails?

I have a Ruby on Rails and ActiveAdmin application. I didn't basically change any default configuration except adding and registering a few models.

I want to enable my application with a route like GET /heartbeat and respond with a simple string to client/user. I'm wondering how could I do the following steps:

  1. Add a custom route to my routes.rb file.
  2. Add a custom controller under app/controllers path.
  3. Implement a custom action and respond to user directly without any view.

Upvotes: 7

Views: 7481

Answers (2)

markquezada
markquezada

Reputation: 8535

Avoiding the Rails render stack will save you some processing and be faster. You can do this at the router level via a simple Rack "application" that returns a response code:

get 'heartbeat', to: proc { [204, {}, []] }

Anything that responds to call and returns [status, headers, body] is rack compliant so you can leverage a proc to do just that, right in the router. In this case, we send a 204 No Content which should be sufficient for a heartbeat, but you can always return custom data/headers.

Update:

I can only imagine that this was downvoted because people don't understand why this is better. Here's a quick attempt to explain:

In case it wasn't clear, you don't need a controller action at all with this method. Here's the equivalent solution to the accepted answer:

get 'heartbeat', to: proc { [200, {}, ['Some string to the client/user']] }

Sticking that line in your Rails routes.rb file will be equivalent to creating a new controller, view and route entry, with one key difference: It avoids the Rails response rendering stack so should be much faster than the accepted solution.

Upvotes: 5

Mareq
Mareq

Reputation: 1351

routes.rb:

get 'heartbeat' => "custom_controller#heartbeat"

custom_controller.rb:

class CustomController < ApplicationController
  def heartbeat
    render inline: "Some string to the client/user"
  end
end

Upvotes: 9

Related Questions