ruby-on-railssinatraapplication-lifecycleobject-sharing

Sinatra/Rails: Persisting custom class instances during app lifetime


Can I assert rails/sinatra apps are initialized only once and all requests share the same app instance? or do new requests spawn new app instances?

Is it possible to instance custom classes and persist them during app lifetime without using sessions, database storages or third party services? If so, what are the implications from a thread-safeness point of view?

I'm trying to figure how to implement a web-based download manager and I'm currently evaluating ruby-based frameworks.


Solution

  • Can I assert rails/sinatra apps are initialized only once and all requests share the same app instance? or do new requests spawn new app instances?

    Not generally. This really depends on your setup. If you only run on process with a server (aka Rack handler) that reuses the same application object, this will work. Whether the same instance of your application is used depends on the web framework you are using. Sinatra for instance creates a new instance of your application class (usually Sinatra::Application) for every request if used as Rack endpoint.

    Is it possible to instance custom classes and persist them during app lifetime without using sessions, database storages or third party services? If so, what are the implications from a thread-safeness point of view?

    If you really want to persist classes, you will probably need something like maglev. However, I believe you mean persisting instances of custom classes. If you don't want to use a database for persistence (you really should), you could fall back to PStore, which ships with Ruby.