rubysinatra

New sinatra object for every requests but initialize only called once


I created a very simple web server through the following script:

require 'sinatra'

class MyApp < Sinatra::Base

    def initialize(app = nil)
        super(app)
        puts "******** constructing myapp **********"
    end

    get '/' do
        return "object id: #{object_id}, class #{self.class}"
    end

end

MyApp.run!

If I run this little web server and then call wget -q -O - http://localhost:4567 for the first time, I see this in my console running my server:

******** constructing myapp **********
127.0.0.1 - - [28/Jan/2017:16:47:39 EST] "GET / HTTP/1.1" 200 31
- -> /

and wget prints:

object id: 10454240, class MyApp

As expected, on the first call, a MyApp object gets created and initialize gets called.

Then, if I do a second call to wget -q -O - http://localhost:4567, I see this:

127.0.0.1 - - [28/Jan/2017:16:49:11 EST] "GET / HTTP/1.1" 200 31
- -> /

And the output of wget prints this:

object id: 9387860, class MyApp

So, on the second call, I have a different instance of MyApp (because object_id does not have the same value as on the frist call) but the initialize is not called. How is it possible to have a new object created and bypassing the call to initialize?


Solution

  • A new class is created for every request.The instance is not reated with Sinatra::Application.new but with Sinatra::Application.prototype.dup that's why initialize is not called every times. See document link for the code.