How to read source code of Rails sample project?

2020-05-29 08:00发布

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.

3条回答
够拽才男人
2楼-- · 2020-05-29 08:27
  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)
查看更多
在下西门庆
3楼-- · 2020-05-29 08:31

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

查看更多
唯我独甜
4楼-- · 2020-05-29 08:33

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 several 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 satisfy 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
查看更多
登录 后发表回答