Search code examples
rubyrack

Making a Rack CLI


I'm trying to make a framework similar to Rails, but purely focused on GraphQL. Once nice feature of Rails is that it provides a CLI interface and a config.ru for Rack. Therefore, you can call rackup or you can call bin/rails server and the Rails app will run. I managed to mimic this functionality by putting the Rack app into a separate file (config/application.rb), which I import in config.ru and in the CLI, then instantiate and run.

However, I have an issue with Rack middleware. Since Rack middleware appears to just magically work when you run use MyMiddleware with an instantiated Rack app, I'm not really sure how I can do this in both config.ru and in my CLI. Right now it looks like I need to instantiate the app in a separate location, add the middleware, then hand it over to config.ru or the CLI. Which, I could do, but it feels like there has to be a way to attach middleware in a cleaner way. For instance, can I require config.ru in some way and then run it? Or can I attach middleware before I instantiate the app?


Solution

  • config.ru is just a ruby file, it's loaded by Rails as part of running each command. You can require it yourself as normal if that's what you'd like to do.

    If you want to really figure out how Rails does it, the config loading is buried in this part of the Rails CLI: https://github.com/rails/rails/blob/3cac5fe94f0f81b4263cfa03d4822c05a55eb49c/railties/lib/rails/application.rb