Using Sinatra’s :app_file option
Last night, two of my patches to Sinatra got merged into the main branch. I’ve already written about the erb_locals feature. The other one was a slightly older one to fix development reloading in situations where Sinatra was not called directly.
The situation which triggered the issue:
- $0 (the file actually run by ruby) was not the file where the Sinatra routing and application was defined
- The file that actually was $0 called ‘require’ on the Sinatra application.
- A Sinatra development environment reload happened.
Ruby prevents duplicate loading of libraries by only loading each require once per lifetime of the VM. If you really do want to reload the file, you have to use Kernel.load. Which of course is how Sinatra handles the development environment’s reloading.
Original code:
Kernel.load $0
New code:
# app_file defaults to $0 Kernel.load Sinatra.options.app_file
Now that app_file is an option, it’s easily overridden in the file with your Sinatra application.
set :app_file, __FILE__
Now development reloading works easier, and Sinatra is a better embeddable framework. No changes are needed to existing applications since app_file defaults to $0, the default behavior is exactly the same as the old behavior.
Leave a Reply