Why does code need to be reloaded in Rails 3? - ruby-on-rails

I am a former PHP developer learning Rails and Sinatra. In PHP, every page request loaded all of the required files. If I changed some code and refreshed the page, I could be sure that the code was fresh.
In Rails 3, Controller code is fresh on every request. However, if I modify any code in the /lib folder, I need to restart the server so the changes take effect.
Why does this happen? Is it something to do with the way Ruby is designed? Is Rails doing some optimizations to avoid reloading code on every request?
Thanks!
Edit: I am mostly interested in what is going on under the hood. Do frameworks like Rails and Sinatra do some special caching for classes? If so, what does they do? Is the default behavior in Ruby that all code gets reloaded on every request? Why do we need tools like Shotgun for Sinatra (http://sinatra-book.gittr.com/#automatic_code_reloading)?

While you are in development mode you should tell Rails not to cache your classes so they reload each time. This means that each request the classes are basically redefined in the rails interpreter. The setting in your Rails.root/config/environments/development.rb:
config.cache_classes = false
The classes the are in your lib/ dir are usually loaded through an initializer and not subject to this setting.
When you move to production you will want all of your classes to be cached so requests are faster and rails will do optimizations to things like scopes on your models.
You could put something in another initializer (maybe called Rails.root/config/initializers/development_reload.rb) that reloads the lib dir with every request in development (or just the ones you are working on):
# file development_reload.rb
if Rails.env.development?
ActionDispatch::Callbacks.after do
load 'filename_in_lib'
# or
Dir.entries("#{Rails.root}/lib").each do |entry|
load entry if entry =~ /.rb$/
end
end
end
I am calling "load" so it actually reloads the file, whereas "require" would just check if it has been loaded and determine it already has so it will not reload it. (I just threw this together and don't use it, but Ruby is extremely flexible and will allow you to do quite a bit.) Use something like this wisely and only in a dev environment.
Why code needs to be reloaded in Rails 3?
Ruby is an interpreted language (JRuby has some support for precompilation, but it's still interpreted). Interpreting the the definition of classes once on initialization is similar to compiling php and deploying in executable format (somewhat). The interpreter is not bothered with redefining classes all the time.
Forcing the explicit reload is an optimization for this type of interpreted language. (if you AOT compile in php you would need to reload the compiled "bytecode" after changes as well; default php uses on-the-fly compilation which is what you are taking advantage of)

How about a more high level approach:
ActionDispatch::Reloader.cleanup!
ActionDispatch::Reloader.prepare!
This was taken from Rails/ActiveRecord v3.2.13 - active_record/railtie.rb
The load approach didn't work for me. Just performing load caused a weird issue where it would trigger certain validators twice for me.
In order to fix that, I tried Object.send(:remove_const, User) before reloading User, but then I lost my observers on that class, so I started chasing my tail.
The above approach reloads all the classes, so maybe there is still yet a better approach to properly remove an individual class from cache and reload it...

Related

Rails: How to autoload constants successfully on first attempt without proper namespacing?

I want the following file structure:
app/components/foo/foo.rb
app/components/foo/_foo.html.haml
app/components/bar/bar.rb
app/components/bar/_bar.html.haml
Where I then can access the different classes like this:
Components::Foo
Components::Bar
Right now, for autoloading to work properly, it has to be structured/coded/accessed like this (hypothetically according to Rails convention):
Components::Foo::Foo
Components::Bar::Bar
That makes no sense. I want the previously mentioned file structure because I want my classes to be self-contained together with any resources/etc. belonging to them. I know that if the ruby file goes right inside app/components all will be well, but that means I have one folder and one file to keep track of, instead of just one folder. Not very nice.
Now, what's bothering me is that, just like the scenario presented here: Rails unable to autoload constant only on first attempt, the autoloading clearly works, but always only on the 2nd attempt. Since it is so systematic, it feels like it should be possible to configure things correct for it to work on the 1st attempt at all times.
This is the only addition I've made to the application.rb:
config.eager_load_paths += Dir[Rails.root.join('app', 'components', '**/')]
I'm aware that a server restart is necessary in case new directories are added/existing directory structure is modified, but that's fine since that doesn't happen very often. Modifying the code obviously happens very often, and while I can keep refreshing the page multiple times until it has re-loaded all the constants, it is very frustrating (and tbh I haven't even tested it in production, but wouldn't be surprised if it does the same thing there on the first load).
I'm also aware that you might be able to work around this by using manual requires etc., and while I haven't had much luck with that anyway, it is still a much inferior solution since it would require a server restart if code is modified (assuming the requiring is done in a central place, such as in an initializer or in application.rb).

How can I find out what prevents a rails app from loading a page?

I have a rails which seemed to be working previously but now after some changes when I go to the root page it takes it infinitely to load it, it just doesn't load it. There're nothing useful in the console either. How can I find out what prevents it from loading the main page? Is it about profiling?
Check your Rails logs, eg. development.rb. You can put logger.info, or puts statements in your environment.rb, development.rb and application.rb files to see how far Rails is getting in the boot process. You can also create a dumb initializer named 00_start_init.rb with a logger.info or puts statement to see if you're getting as far as initialization. I've found that useful before.
To really understand where you application is hanging, you need to understand the Rails initialization process. Here is the documentation for Rails version 4.2. http://guides.rubyonrails.org/v4.2/initialization.html. Similar documentation exists for every version of Rails. You can take advantage of understanding the boot sequence by placing log statement at various point in the process.
I'm assuming you're in the development environment. If so, and the console loads, it's likely not a configuration problem. It's more likely a problem with your controllers or models. If the console won't load to a prompt, then it's likely a configuration problem in application.rb, development.rb, an initializer, etc.
You mention profiling, but provide no details about it. I can't even guess what you're referring to, so the answer is "maybe?". If you can post the code changes you made since the app last loaded in the browser, that would make it much easier to help you trouble-shoot.

confusing about autoload_paths vs eager_load_paths in rails 4

I read a post about the rails load_paths, here is the link.
But, I am still confused about the difference between the autoload_paths and eager_load_paths:
I have tested them in a newly created Rails 4 project. It seems that they run the same way, that auto-reload in the development mode but in the production mode.
Author of the linked article here. Here's an attempt to clear up the confusion, going off of #fkreusch's answer.
In Ruby you have to require every .rb file in order to have its code run. However, notice how in Rails you never specifically require any of your models, controllers, or other files in the app/ dir. Why is that? That's because in Rails app/* is in autoload_paths. This means that when you run your rails app in development (for example via rails console) — none of the models and controllers are actually required by ruby yet. Rails uses special magical feature of ruby to actually wait until the code mentions a constant, say Book, and only then it would run require 'book' which it finds in one of the autoload_paths. This gives you faster console and server startup in development, because nothing gets required when you start it, only when code actually needs it.
Now, this behavior is good for local development, but what about production? Imagine that in production your server does the same type of magical constant loading (autoloading). It's not the end of the world really, you start your server in production, and people start browsing your pages slightly slower, because some of the files will need to be autoloaded. Yes, it's slower for those few initial requests, while the server "warms up", but it's not that bad. Except, that's not the end of the story.
If you are running on ruby 1.9.x (if I recall correctly), then auto-requiring files like that is not thread safe. So if you are using a server like puma, you will run into problems. Even if you aren't using a multi-threaded server, you are still probably better off having your whole application get required "proactively", on startup. This means that in production, you want every model, every controller, etc all fully required as you start your app, and you don't mind the longer startup time. This is called eager loading. All ruby files get eagerly loaded, get it? But how can you do that, if your rails app doesn't have a single require statement? That's where eager_load_paths come in. Whatever you put in them, all the files in all the directories underneath those paths will be required at startup in production. Hope this clears it up.
It's important to note that eager_load_paths are not active in development environment, so whatever you put in them will not be eagerly required immediately in development, only in production.
It's also important to note that just putting something into autoload_paths will not make it eager-loaded in production. Unfortunately. You have to explicitly put it into eager_load_paths as well.
Another interesting quirk is that in every rails app, all directories under app/ are automatically in both autoload_paths and eager_load_paths, meaning that adding a directory there requires no further actions.
Basically, autoload_paths are paths Rails will use to try loading your classes automatically. E.g. when you call Book, if that class isn't loaded yet, it will go through the autoload_paths and look for it in those paths.
In production, it might be better to load those upfront to avoid autoload concurrent issues. For that, it provides the eager_load_paths. Paths in that list will be required upfront when your application starts.

Ruby and/or Rails caching require()'ed scripts?

I'm testing out a basic Rails app and I seem to be getting some undesirable caching behavior on a library script that's being require()'ed into my controller script.
Suppose FooController.rb contains the following:
require 'utils' # a library script
class FooController
def some_action
#some_member = do_something() # global method defined in utils.rb
end
end
It appears that changes to utils.rb do not take effect until I restart the Rails server. I don't believe this is due to a misconfiguration of Rails' class caching, since a) I am running in a "development" environment, and b) I can make changes directly to the controller code (e.g., to the some_action method above) that are reflected upon the next execution of the script. I've been testing this with some calls to puts that spam messages into the console.
Is there some behavior in either Ruby or Rails that would cause require()-ed scripts to remain cached? If so, is there a way to configure that behavior?
Rails class reloader is relatively naive. I believe it's only intended to reload things like controllers and models, leaving anything you might be require'ing into your project alone. So, if you have some custom code in the lib directory or elsewhere that you have changed it is expected behavior for you to have to restart the Rails server.
If you want to require each time the code is encountered, you really want load.
http://www.ruby-doc.org/core/Kernel.html#method-i-load

why might rails-2.3.5 not reload some files under app in development mode?

I've added a subdirectory app/renderers after Railscast #101. The classes in that directory are not getting reloaded by my development server. It's driving me a little bonkers.
I've read everything I could find on forcing it to reload lib and/or plugins but this seems to be a different case since "everything under app should be reloaded automatically." Plus, I've checked ActiveSupport::Dependencies.load_once_paths, and app/renderers definitely isn't in it.
I'd also like to get the renderers to be automatically required, so that I don't have to go around putting require statements in the rest of my code. Is that sensible? How does it work for, say, models and other constants?
Doh. I should have been loading the files, not requiring them.
I'd still like to have them magically loaded -- not needing a specific load statement for each one -- but for now it's working :)

Resources