title

Don't do this! Top mistakes you should avoid as a strong Ruby on Rails Developer.

Aug 17, 2022
Blog.png

Rails is a powerful and human-friendly framework. Its guiding principles place a strong emphasis on convention over configuration, allowing new Rails applications to be up and running in a fraction of the time required for applications written in many languages. 

However, the ease of use that Rails provides can be a detriment, and not only for newbies devs. In this article, we'll look at a few of the most common Rails development mistakes and provide advice on how to avoid them in your own coding adventures, so let's get started!

Mistake #1: Are you following a Proper Naming Convention? 

You definitely know that but let’s set up a quick reminder about this one. Keep the following points in mind when developing Rails projects to avoid future problems: 

  • The model's name should be singular.
  • To automatically map your model and table, ensure that all available tables are plural.
  • You should not reserve names for your class.
  • To avoid complexity, always take the default restful routes.

Let’s look on a simple example, which states that model names should be singular and clear.

# Bad
class Pay
end

# Good
class Payment
end

We won't be stopped on this more. Let’s go further.


Mistake #2: Keep It Clean, remember? 

Cleaning up your code, also known as refactoring, means improving the quality of your code without changing its behavior. Code styles can differ among developers, in addition to being easier to read and maintain. By adhering to a few stylistic guidelines, you can keep development moving when bringing on new developers to your project. 

Top stylistic guidelines are as follows:

  • Space Indentations

Using two space indentations instead of four space indentations is one of the simplest and most widely accepted Ruby on Rails best practices. Furthermore, most Ruby on Rails developers agree that tabs should never be used, including mixing tabs and spaces. Long strings of code will be easier to read and maintain as a result.

  • Use question marks to define predicate methods

Using a '?' to define predicate methods is one of the best Ruby on Rails tips for keeping your code readable. Predicate methods always return one of two values: true or false. Predicate methods in Ruby on Rails are named with a question mark at the end.

To put this into practice, if you have a class called 'invoice' and want to write an instance method that returns whether or not the invoice has been paid, you would call it 'paid?' 

  • Use 'Unless' instead of '!if' In Conditional Statements 

One of the best Ruby on Rails tips for writing conditional statements with a negative condition is to use 'Unless' instead of 'If'. 'Unless' is unique in Ruby on Rails and helps to create readable code. Let’s look on example below: 

Usually, you might use it:

if !true
  do_this
end

But let’s change it to “Unless”. See the difference - much proficient, isn’t it? 

unless true
  do_this
end

Mistake #3: Putting too much logic in models

Developers overwhelm models with logic such as email notifications, data conversion from one format to another, and so on. Because this core functionality can be handled by services such as plain Ruby objects, it can be removed from ActiveRecord.

What should you do?

  • Use configuration (i.e., relations and validations)
  • Simple mutation methods for updating a few attributes and saving them in the database
  • Access wrappers are used to conceal internal model information.
  • You should never use the method or any other query building outside the model class in sophisticated queries.
  • Be sure you store your business logic in service objects. 

Mistake #4: Using an excessive number of gems

Ruby and Rails are both supported by a robust ecosystem of RubyGems that provide developers with nearly any capability they can imagine. While this is an excellent resource for quickly building a complex application, it can result in many bloated applications due to an excessive number of gems in the application's Gemfile.

Excessive use of gems may cause a Rails process to be larger than necessary. As a result, application performance may suffer in the production environment, and other runtime issues may arise. As a Ruby developer, you should consider each gem carefully before incorporating it into your code.


Mistake #5: Missing scopes

You can use scopes to hide the database implementation and uniqualize the code. Furthermore, the code becomes much more readable because it reveals the developer's intentions rather than the database structure.

Bad: 

def index
 @lessons = Course.lessons.order(position: :asc)
end

Good: 

class Lesson < ActiveRecord: :Base
 Belongs_to :course
 
 scope :by_position, -> { order(position: :asc) }
end

def index
 @lessons = course.lessons.by_position
end

Mistake #6: Keep Your credentials.yml Encrypted

Your application may use external services such as Google Calendar, Stripe Payment, or AWS, and the API keys or credentials for these services are stored in the credentials.yml or secrets.yml files.

When the file is accidentally checked into the source code repository with the rest of your application, anyone with access to the repository can now easily compromise all users of your application.


Mistake #7: Not Setting Default Fields In Migrations

If a field model must have a default value, it should be installed via the database. It’s simply described by this example: 

Don’t do this: 

clas Article
 after_initialize :set_default_status
 
 def set_default_status
  self.status = 'pending'
 end
end

Do this instead: 

clas MyMigration
 def up
  change_column :article, status :string, default: 'pending'
 end
  
 def down
  change_column :article, status :string
 end
end

Mistake #8: Not using memoization

Memoization is a technique for increasing your assessor's speed during Ruby on Rails development by caching the results of time-consuming methods or variable initialization.

Memory uses the ||= operator for some parameter value and then initializes the cache variables.

Let’s take a look on example below: 

def google_calendar_event
 @event||=GoogleCalendarEvent.fing_by(event_id:params[:event_id]}
end

Mistake #9: Avoid Blocking on Calls

It is simple to integrate APIs using third-party Rails application providers, but it can be slow at times. Instead of calling services from your Rails application, move some code to the background job to avoid call blocking.

The two most popular Rubygems for application development for this purpose are Delayed Job and Sidekiq.

When a new user creates an account and provides a phone number, for example, your application may use a third-party service to authenticate the multi-factor confirmation code.

When using the send authentication code method, the following code snippet is used:

def send_authentication_code(number, code)
 account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
 auth_token = "your_auth_token"
 
 @client = Twilio::REST::Client.new account_sid, auth_token
 massage = @client.messages.create(
  body: code
  to: number,
  from: ENV['TWILIO_NUMBER'])
  
 puts message.sid
end

When the third-party service request is executed, you put your application at risk by calling send authentication code.

Integrate a job system that can store and implement work BTS in your main application threads to avoid this risk.


Mistake #10: Use Enums With Caution

Using enums strategically is one of the best Ruby on Rails tips developers can use. Assume you have a 'Invoice' model and a column/field where you want to store the status of whether it's pending, overdue, or paid. You could do something like this:

if invoice.status == "pending"
Do_something
elsif invoice.status == "overdue"
Do_something
elsif invoice.status == "paid"
Do_something
end

Or maybe this: 

if invoice.status == 0 #pending
Do_something
elsif invoice.status == 1 #overdue
Do_something
elsif invoice.status == 2 #paid
Do_something
end

Let's look at the same model with enums now. Remember that you want to define the status of a column with an integer, not null, and define the default value of your model's status after you've created it (i.e. default: 0). Enums in your model can be defined as follows:

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

You can now rewrite this code as: 

if invoice.pending?
Do_something
elsif invoice.overdue?
Do_something
elsif invoice.paid?
Do_something
end

Gorgeous, isn’t it? If another developer joins your team, they will immediately recognize the predicate methods with names. It also provides methods for switching between defined statuses.

Mistake #11: Lack of automated tests

Ruby on Rails is a powerful and intuitive application framework that includes automated testing by default. Rails developers write practical tests in a variety of styles, such as BDD and TDD, to make the test frameworks even more powerful.

There are numerous debates about how thorough your testing should be, demonstrating the importance of automated testing for every application.

Your application must include at least one high-level integration test written for your controllers to edit and modify the code of your Ruby on Rails version, as well as a clear delineation of the Ruby application's entire set of functionality.

🚀 And don’t forget: Keep Your Code DRY 

INTEGU-No-Comments-For-Clean-Code.jpg

You should be aware of issues that can make your application less secure, less reliable, and perform worse. 

If you are already familiar with this list of mistakes and already knew about these ones, that’s great : 👉Dev’s League is waiting for you. Keep it rockin and don't stop improving your hard skills (and don’t forget about work-life balance)


Become a Devler: text us on Telegram and explore the opportunities to be a successful software engineer.

Keep reading

Apr 08, 2024

Innovate or Stagnate: Why AI and AR Are Essential for Modern Marketing

Is your marketing stuck in the past? In 2024, marketers are no longer driven by the desire to get occasional money from an occasional customer once a year. No-no. This isn’t the grandfather’s marketing of billboards, generic one-size-fits-all ads, and one-time transactions anymore. Instead, businesses are interested in building lasting relationships with customers. The combination of AI's processing power and AR's ability to overlay information is propelling this shift. Read further to learn more about the benefits of AR and AI in marketing and discover the best tips for your marketing strategy. Buckle up because the future of marketing is here!
Mar 06, 2024

UI/UX Design for FinTech: Must-Known Practices and Case Studies

Read our guide on UI/UX applications for fintech and banking. Learn how to play by modern tech and design rules and harness the power of user-centered design principles!