Ruby on Rails Best Practices Every Developer Should Follow

Deborah Cohen

Developer using Ruby on Rails best practices
Ruby on Rails Best Practices Every Developer Should Follow

Whether you’re a seasoned web application developer, or you’re just starting, chances are you’ve heard of Ruby on Rails. This robust web application framework can help you save time while coding and focus on what you’re building, rather than the technology behind it. Rails is particularly noted how easily it lends itself to collaboration and how easy it is to maintain. 


The Rails framework helps make developing complex projects more efficient by providing developers with a library of code with ready-made solutions for tasks that would normally be time-consuming. Building web forms, menus, tables and more is made easier, and quicker than ever. 

So, how do you harness the efficient and robust power of Rails? By following a pre-determined set of Ruby on Rails best practices suggest by seasoned developers and Rails itself.

That’s why we’re sharing our best Ruby on Rails tips. In addition to saving you time on menial tasks, they’ll help ensure you don’t stray from the framework, meaning your application will be easier and cleaner to manage. Following best practices will help you create a project that is simpler to scale since any new developers you bring on will be able to jump in with ease. 

Following these best practices is beneficial for several additional reasons, including:

  1. Maintainability
  2. Readability
  3. Elegance
  4. Efficient Development
  5. DRY code

Ready to dive in? We thought so.


Ruby on Rails Best Practice: Keep It Clean

There’s good, bad, and even ugly when it comes to just about any programming language. Ruby on Rails is no exception. There’s a few widely agreed upon stylistic guidelines among Ruby on Rails developers that’ll help you leap from functional spaghetti code to clean, robust, efficient code.

Cleaning up your code, also known as refactoring, means the quality of your code will be improved without changing its behavior. In addition to being easier to read and maintain, code styles can vary among developers. Staying within a few stylistic guidelines means you can keep development in high gear when bringing on new developers to your project. 

These are our top stylistic guidelines:

  1. Space Indentations
  2. Use Question Marks to Define Predicate Methods
  3. Use ‘Unless’ Instead of ‘!if’ in Conditional Statements


Space Indentations

One of the easiest and most widely agreed-upon Ruby on Rails best practices is to use two space indentations instead of four space indentations. Additionally, most Ruby on Rails developers agree on never using tabs, which includes not mixing tabs and spaces. This will keep long strings of code easier to read and maintain.

Communicating this, and other stylistic guidelines for code is made easy with CloudApp for developers. You can create clear documentation showing your team how to properly implement these Ruby on Rails tips and tricks with annotated screenshot and screen recordings.


Use Question Marks to Define Predicate Methods

One of the best Ruby on Rails tips to keep your code readable is to use a ‘?’ to define predicate methods. Predicate methods always return either true or false. Ruby on Rails has a naming convention where predicate methods end with a question mark.

To put this into practice, if you have a class called ‘invoice’ and are writing an instance method that would return whether or not the invoice has been paid, you would name the method ‘paid?’. This helps improve the readability of code, making it read more like English.


Use ‘Unless’ Instead of ‘!if’ in Conditional Statements


When it comes to writing conditional statements with a negative condition, on the of the best Ruby on Rails tips is to use ‘Unless’ instead of ‘If’. ‘Unless’ is exclusive in Ruby on Rails and keeps in line with creating readable code. For example, you may have code that says

If !true
Do_this
End


Instead, use ‘Unless’ like this


Unless true
Do_this
End


However, in the event you need to involve an ‘else’ in your conditional statement, don’t ever use ‘unless-else’.

For example, you may have code that reads something like this: 


Unless condition
#throw error
Else
#return success
End


Instead, we recommend the following:


If condition
#return success
Else
#throw error
End


Keeping your code clean and readable may seem like more effort initially. However, it’ll save you time and headaches in the future when you have long strings of code to manage.


Testing Best Practices for Ruby on Rails

If you’re familiar with Ruby on Rails, then you know how quintessential Ruby developers consider testing. This can seem like a difficult obstacle for new Ruby on Rails developers to overcome. We get it, writing code to test your Ruby on Rails applications can be difficult and time-consuming. However, these drawbacks don’t make testing any less important in software development.

Yes, writing tests on Ruby on Rails first can seem like a hassle. However, once they overcame that hurdle, many developers claim they began building features in no time. If you want to be an excellent Ruby developer, you’re going to need to develop your testing skills.

In addition to helping you catch and fix bugs beforehand, testing can give developers confidence they didn’t break any code when refactoring or making performance enhancements. If you’re bringing on new developers to your project, testing means you’ll have already detailed specifications of a feature or app which can act as documentation, helping them understand why you implemented that code. Once you get the hang of it, testing can save your team time and money in the long run.

In addition to these testing best practices for Ruby on Rails, we recommend using a great screen recording application like CloudApp to save you time while testing with your team. Did you know power users of CloudApp saw upwards of 67 minutes saved per week while using its screen recording, screen snipping and GIF editing/creation tools? If your team does find a bug, they can communicate it faster, keeping your team in the loop and making testing in Ruby on Rails that much simpler.


Ruby on Rails Best Practice: Keep Your Code DRY

Ruby on Rails’ object-oriented principles are built to help you avoid duplicating code throughout your web application. Whenever possible, a great Ruby on Rails tip is to re-use as much code as possible instead of repeating similar code in many places. This follows the ongoing theme of creating clean, readable and maintainable code whilst reducing errors. Code that is written with the DRY principle is easier to read and takes less time to write. If you’re only writing a piece of code in one place, when you inevitably go to change it, it won’t require shotgun surgery.

Rails’ website states this principle as: “Don't Repeat Yourself: DRY is a principle of software development which states that "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system." By not writing the same information over and over again, our code is more maintainable, more extensible, and less buggy.” 


Ruby on Rails Best Practice: Fat Model, Skinny Controller

If you’re familiar with Ruby, you’ve likely heard of Fat Model, Skinny Controller. This also follows the DRY principle because you write the code in your model and the controller only to the call like this:

Example of fat model, skinny controller
Fat Model, Skinny Controller follows the DRY principle. Code example from: https://riptutorial.com/ruby-on-rails/example/3932/don-t-repeat-yourself--dry-


Another Ruby on Rails tip is to keep non-response related logic out of the controllers. This includes business logic or persistence/model changing logic. However, sometimes there will be logic that doesn’t seem to fit into the context of any model or controller. In this instance, you’ll have to use your judgment to figure out where the best placement would be. Some Ruby on Rails tips and tricks to figure out where it would fit include:

  • Ensuring your controllers are only making simple queries to the model
  • Move any code that isn’t related to response and request out of that model
  • Use PORO (Plain Old Ruby Objects) Ruby classes if the logic is of a specific domain and doesn’t fit the context of a model
  • Use modules if you need to extract a common functionality from otherwise unrelated functionality.


Ruby on Rails Best Practice: Use Enums Wisely

One of the best Ruby on Rails tips developers can use is implementing enums strategically. For example, let’s say you have a model called ‘Invoice’ and a column/field where you want to store the status of whether it’s pending, overdue or paid. You might write something like this:


If invoice.status == “pending”
Do_something
Elsif invoice.status == “overdue”
Do_something
Elsif invoice.status == “paid”
Do_something
End

Or


If invoice.status == 0 #pending
Do_something
Elsif invoice.status == 1 #overdue
Do_something
Elsif invoice.status == 2 #paid
Do_something
End

Now, let’s take a look at this same model with enums. Keep in mind, you want to define the status of a column with an integer, and if you can, not null, and define the default value of your model’s status after you’ve created it (i.e. default: 0). You can define enums in your model like this:


Enum status: { pending: 0, overdue: 1, paid: 2 }

Now, you can re-write this code as:


If invoice.pending?
Do_something
Elsif invoice.overdue?
Do_something
Elsif invoice.paid?
Do_something
End


Now, isn’t that a beautiful piece of code? If another developer joins your team, they’ll have no trouble seeing the predicate methods with names. It also gives you the methods to switch between defined status.


Ruby on Rails Best Practice: SQL Injection Prevention

This may be a common concern among Ruby on Rails developers, however, preventing vulnerabilities in your web application is quintessential to keep your entire database safe.

If you’re not familiar with the term, SQL injection, or SQLI, is a common attack on your backend database when malicious SQL code is manipulated. This means a user can access information that the creator didn’t intend to be displayed, or worse, changed.

Failing to prevent SQL injection means your entire database could be at risk of encountering malicious content.

Yikes.

So - how do you prevent this?

Well, there are many ways to prevent SQL injection in Ruby on Rails. However, single parameters are one of the most common use cases for Ruby on Rails queries. For Example:

# Unsafe
User.where("email = '#{email}'")
User.where("email = '%{email}'" % { email: email })
 
# Safe
User.where(email: email)
User.where("email = ?", email)
User.where("email = :email", email: email)


Code from: http://gavinmiller.io/2015/fixing-sql-injection-vulnerabilities/


Line 3 and 8 may look similar, however, line 3 uses string formatting while line 8 uses parameterization. Parameterization is a simple way to protect against SQL injection in Ruby on Rails. Keep in mind if you need to add quotes around a query, it is susceptible to SQLI. Keep your queries parameterized to ensure your database stays safe.


Conclusion

The best Ruby on Rails tips or tricks includes following best practices defined by the framework and community of seasoned developers who’ve learned the best, most efficient ways to write code. Fortunately, the Ruby on Rails community is known for being amazing - part of the reason why Ruby developers love it as much as they do.

When used within the guidelines of these best practices, building and maintaining your web application with Ruby on Rails can be an efficient, clean and fun project for yourself and any other developers who jump in on your project. While you’re working on building your Ruby on Rails skills, don’t forget to download a free CloudApp version to see how it can save you time and improve communication for your development team.

Join the Discussion