views:

92

answers:

3

I have been using the Rails console a fair bit lately and its making me curious. Commands like

>> app.get("/")
=> 200
>> app.html_document.to_s

make me curious about how does Rails works in memory. Can anyone explain what's going in there? What objects are getting instantiated when and when do they get destroyed?

A: 

That question is a little too complicated to answer. There's probably a ton going on, depending how complicated the app is.

Ruby allocates memory for objects it needs to create on the fly. When objects drop out of scope, they are marked unused and the garbage collector frees the memory.

However, class variables and global variables, etc can prevent objects from dropping out of scope.

I wouldn't worry about it too much. If you ever have memory issues in a production application, just switch to Ruby Enterprise and many of them will magically go away. :)

Steven Soroka
A: 

On a more general note, _why wrote an excellent piece on Ruby memory management / garbage collector some years ago.

Jonas Elfström
A: 

After a little time and a lot of reading, here is a minimal answer to my own question since this is still being viewed by a steady trickle of people. Keep in mind that I am still new to Rails and this is simply my understanding of it after about two months of working with it.

What get instantiated when is effected by your environment settings because class loading (among other things) is handled quite differently in development vs production. The bare essentials can be gleaned from reading the comments the files in config/environments/

# In the development environment your application's code is reloaded on
# every request.  This slows down response time but is perfect for development
# since you don't have to restart the webserver when you make code changes.

and

# The production environment is meant for finished, "live" apps.
# Code is not reloaded between requests

Aside from that, general flow is illustrated in all the typical MVC diagrams (dispatcher > controller > model > controller > view ) and while true, there are tonnes of other classes instantiated along the way. An exhaustive list would be exactly that, exhausting.

For those interested in the details (at least all the details that matter) but not sure where to go, the book "The Rails Way" by Obie Fernandez is very worthwhile and deals with this rather extensively.

Mike Williamson