Convention Over Configuration
In Rails you find yourself looking at controllers, views and models for your database.
In order to reduce the need of heavy configuration, Rails implements rules to ease up working with the application. You may define your own rules but for the beginning (and for later on) it's a good idea to stick to conventions that Rails offers.
These conventions will speed up development, keep your code concise and readable and allow you an easy navigation inside your application.
For Example
If you have a database table called orders
with the primary key id
. The matching model is called order
and the controller that handles all the logic is named orders_controller
. The view is split in different actions: if the controller has a new
and edit
action, there is also a newand
edit` view.
Don't Repeat Yourself (DRY)
To help to maintain clean code, Rails follows the principle of DRY.
It involves whenever possible, re-using as much code as possible rather than duplicating similar code in multiple places (for example, using partials). This reduces errors, keeps your code clean and enforces the principle of writing code once and then reusing it. It is also easier and more efficient to update code in one place than to update multiple parts of the same code. Thus making your code more modular and robust.
This also helps lead to an API driven structure where internal methods are hidden and changes are achieved through passing parameters in an API fashion.
Fat Model, Skinny Controller
“Fat Model, Skinny Controller” refers to how the M and C parts of MVC ideally work together. Namely, any non-response-related logic should go in the model, ideally in a nice, testable method. Meanwhile, the “skinny” controller is simply a nice interface between the view and model.
In practice, this can require a range of different types of refactoring, but it all comes down to one idea: by moving any logic that isn’t about the response to the model (instead of the controller), not only have you promoted reuse where possible but you’ve also made it possible to test your code outside of the context of a request.
Let’s look at a simple example. Say you have code like this:
def index
@published_posts = Post.where('published_at <= ?', Time.now)
@unpublished_posts = Post.where('published_at IS NULL OR published_at > ?', Time.now)
end
You can change it to this:
def index
@published_posts = Post.all_published
@unpublished_posts = Post.all_unpublished
end
Then, you can move the logic to your post model, where it might look like this:
def self.all_published
where('published_at <= ?', Time.now)
end
def self.all_unpublished
where('published_at IS NULL OR published_at > ?', Time.now)
end
Sign up or log in
Save edit as a guest
Join Stack Overflow
We recognize you from another Stack Exchange Network site!
Join and Save Draft