Why does Rails generate config.ru, which runs the class, and not the object?

Rack indicates

A Rack application is a Ruby object (not a class) that answers a call.

Therefore, a simple config.ru looks like this:

 class MyApp def call(env) [200, {"Content-Type" => "text/plain"}, ["Hello from Rack!\n"]] end end run MyApp.new 

while Rails generates this:

 # This file is used by Rack-based servers to start the application. require ::File.expand_path('../config/environment', __FILE__) run RailsApp::Application 

So I'm wondering: why not run RailsApp::Application.new when Rack indicates that it is an object, not a class? Is there something special about Rails::Application that I am missing?

+8
ruby ruby-on-rails rack
source share
2 answers

It really is a little hidden :)

RailsApp::Application is a child of the Rails::Application class, which in turn is the Rails::Engine , which is the Rails::Railtie . Now Rails::Railtie has an inherited hook that is called whenever the child class inherits the Railtie class (in this case, Engine ).

This callback includes the Rails::Railtie::Configurable module in a subclass. In this module you will find the first part of magic.

The method_missing method, which is defined in the class, calls the method in the class instance, which more or less allows

 RailsApp::Application.new.call(...) 

This call instance method is defined in Rails::Application#call and performs a typical rack transfer.

There is probably still a bit more magic, which makes it not the equivalent of 100%, but it should be something like this ...

+15
source share

The class is also an object. Rack does not instantiate the application object (which is why it indicates that you need to provide the object), you do it in config.ru , therefore, if the Rails class class follows all Rack rules, when Rack sends a β€œcall”, it should not be a problem.

Inside, I don't know if Rails does anything special on call . It could even be a factory method that spits out an instance of an application class and runs it. But it is not necessary to satisfy Rack.

+1
source share

All Articles