views:

682

answers:

3

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.

+1  A: 

Rails code are primarily ruby code. Master in ruby and you will have no problem at all reading rails code. Good luck.

Ricardo Acras
Yes, I agree. But is there any rails magics happened in this process should be explained to newbie like me? Or is there easy way to identify where a strange method comes from?
eric2323223
+4  A: 

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
Samuel
A: 
  1. 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
  2. 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.
  3. I like to look at the tests first going from top to bottom (integration, controller, model)
Kafka
Looking at test is a good point, vote up:)
eric2323223