Reading source code of sample projects, such as Beast and Bort, are recommended as a good way to learn rails. But I found myself getting lost in reading source code of these projects, cause the included plugins might bring in some strange code without any hint, such as "require"
or "include"
. Could you share your rails code reading experience? Lots of thanks ahead.
views:
682answers:
3Rails code are primarily ruby code. Master in ruby and you will have no problem at all reading rails code. Good luck.
When learning to use rails, one of the most important things to know is how it loads the code you've written. Let's say you have a HelloController in the app/controllers/demo/sub directory. If you generated this controller, it will have the correct name of Demo::Sub::HelloController.
When your route tells rails to look for "demo/sub/hello", that is translated into the controller's full name (Demo::Sub::HelloController) which rails will they try to call. Ruby cannot find this class and calls const_missing which makes rails translate the name into a file, in this case demo/sub/hello_controller (:: = /, capitals other than first = _, look for Inflections under underscore method). Rails then requires this file and checks for the correct class definition.
Rails adds serveral directories into the ruby's load path (app/controllers, app/models, app/helpers, lib, vendor) and a demo/sub/hello_controller.rb in any of these directories will satsify the require. But controllers not in app/controllers will need special care for there views.
Also, this works for the namespaces, only it will look for a directory. So referencing Demo::Sub will look for the demo/sub directory. This allows you to forgo the standard definition of classes, so you can do
class Demo::Sub::HelloController < ActionController::Base
end
instead of
module Demo
module Sub
class HelloController < ActionController::Base
end
end
end
- Develop a simple rails project until you have the basic Rails stuff down. Because once you know standard Rails you are going to recognize plugin functionality quicker
- Get to know ruby better, since Rails is written in it. E.g there is a book called Ruby for Rails, which is a good starting point.
- I like to look at the tests first going from top to bottom (integration, controller, model)