Some basic rules to follow, for diff. rails components. Please add comment if you want to add anything.
##Controllers
- Extract common code in controller action, which loads data from DB using finder methods with params as arguments.
- Same for any service object loading.
- Above two cases, if being used in more than one controller, then define a concern using included do
before_action :finder_method end
and include that in both. - Do not write separate controller for API, instead use respond_to with diff. data format.
- Single instance variable per action.
- Extract any code which is not rails related, as a separate ruby class which can be used as a reusable utility. Like, CsvImporter, PaypalUtil, GoogleAnalyticsUtil etc. Do not extract all business logic as service/util, that is not necessary.
- Extract more controllers, based on the workings of your actions. Do not put all actions in one controller.
##Models
- define concerns/modules for diff. DB columns to keep them separated using
included do has_one :model_name end
block. Same as point 3 of controllers. - Use ActiveRecord queries properly, do not use it in loops. Instead we can use SQL queries when needed to optimize the execution time.
- Understand when model gives you AREL object, and when ruby object, based on what AR methods you have called.
- Understand aggregate functions, ordering/sorting, inner join, left/right outer join etc. This will be very helpful.
##Views
- Never use
%img
, only use= image_tag
- Use helper classes, define methods, when there is some ruby logic needed in templates.
- Always use HAML if possible, that is easy to write.
- Use partials properly when needed.
- Use diff. views for diff. types of format - .js.haml, .html.haml etc.
js.erb
does not work.
##Javascripts
- Controller/action specific Javascript, which should load only on that controller/action. Using Object literal pattern, do not add document.ready at any random place.
- Never use asset images using static URLs in JS, instead make CSS classes and use them. js.erb does not work!
- Always use manifest files for point 1.
##CSS/SCSS
- Use SCSS if it has urls for assets, use helpers like font-url, asset-url for them.
##Routes
- Always define routes using specific method - get/post/put/patch/delete etc.
- Always use resources or module when needed, do not use match unless it is required for multiple methods like get n put both.
##Tests/specs
- Define tests for each model, controller and service/util classes.