Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
like image 547
moorara Avatar asked Nov 22 '15 16:11

moorara


People also ask

How do I create a controller in Rails?

To generate a controller and optionally its actions, do the following: Press Ctrl twice and start typing rails g controller. Select rails g controller and press Enter . In the invoked Add New Controller dialog, specify the controller name.


2 Answers

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
like image 54
Mareq Avatar answered Sep 28 '22 05:09

Mareq


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.

like image 23
markquezada Avatar answered Sep 28 '22 05:09

markquezada