What is this Rack? - Veltris

What is this Rack?

November 29, 2020 |

    We as developers use frameworks like Rails, and while using it everything seems like magic to us because of abstraction. But have you ever thought of how the internal Request/Response cycle works in this Rails framework Or who is the one driving it internally ?

    RACK is the one which is responsible for handling all these things.

    But what is this RACK??

    Rack is the middleware which helps application server to run your rails app. You can think of it as a common language that both your app server and rails application understands. So, our app server interacts to our rails application using rack(translator).

    Request Response Flow

    RACK INTERFACE IMPLEMENTATION

    Rack defines a simple interface and it must have these three properties:

    1. It must respond to Call method
    2. Call method takes a single argument, termed as env/environment. This env contains all the data about the request
    3. Call method returns an array of three elements which is [status, headers, body] of the response

    Let’s understand the above mentioned points by writing a simple rack complaint application, which returns the text “Hi, I am RACK”

    require 'rack'
    require 'thin'
    class RackApp
      def call(env)
        [ 200, { "Content-Type" => "text/plain" }, ["Hi, I am Rack"] ]
      end
    end
    Rack::Handler::Thin.run RackApp.new

    In the above example we can see that RackApp is a class which has one instance method termed as call which takes env as an argument and returns an array containing three elements:

    This array consists of following three elements:

    1. Status Code: 200(HTTP “OK” status)
    2. Header: Content-Type(text/plain)
    3. Body: [“Hi, I am Rack”]

    Note: One thing to focus on, is that Body of the response([“Hi, I am Rack”]) must respond to each, thats why normal string is enclosed in an array and then returned.

    But in case of some type of IO object this enclosing inside array is not required.

    ❤️ Like, Share or Leave A Comment!

    Well, thats all for this blog, Hope you find it informative. If you liked it, please click the 👏🏼 button and share it with others! Feel free to leave any comments.
    For more such blogs … stay tuned.

    Happy Coding …

    Thanks

    Related Articles