How to write maintainable routes in rails


Bookmark and Share

config/routes.rb is the gateway to your ruby on rails application. All request send by your users are directed to the appropriate code by the routes.

Example:

When someone visits your-website.com/profiles then the request is taken to the Index action of the UsersController. Under that action you will get the index.html.erb. So using routes we have configured the UsersController to respond to the users request it is its responsibility to do it now.

We can declare routes in various ways:

Since there are multiple ways to declare routes (as all forms are right), its best to stick with a single method for the code to be more readable. routes.rb is going to be one of the most heavily edited file in your project as when ever you add a new page or create a new form, you need to add a route to access the page or an end-point to accept the request. So it is most likely that your routes.rb file will start to grow ugly:

So here we will share some tips to write proper, maintainable routes:

First important point to note is that, its best to write routes as resources
eg:

 

declaring resources will create the following 7 routes.

Read More

Lambda vs Proc Vs Blocks


Bookmark and Share

The difference between these three is one of the most baffling concepts to grasp while anyone starts to learn ruby. Since at Red Panthers we recruit and build our own team from freshers, we too will be blogging about it here to make it easy for the beginners.

But before we state the difference between the three, let me explain what all these three does to make it easy for you.

Blocks: They are called closures in other languages, it is a way of grouping code/statements. In ruby single line blocks are written in {} and multi-line blocks are represented using do..end

An interesting fact about ruby is that all methods in ruby accept a block, even if you don’t declare a variable to accept it. So for example, take the method below

It can accept a block as below

The code is valid, but the output will have only puts “Hello World”.

Why? because we passed in the block but it is not getting called. To run the block passed within your method you need to use the yield command.

Now it will print

But since we placed yield, it would now be expecting a block to be always passed in. So we need to …

Read More

Lazy enumerator to handle huge files


Bookmark and Share

Lazy evaluation, or call-by-need is an evaluation strategy which delays the evaluation of an expression until its value is needed. It’s frequently seen in functional languages, ruby introduced the lazy method in Ruby 2.0. For those who don’t know what are enumerators: enumerators are something that can be counted. So a collection of elements, files (file is an collection of lines of string), etc can be treated as an enumerator.

In ruby we need to make something countable into an enumerator object, which is done by applying .each and .map on it.

Ruby has a wide range of operations we can do over a collection, it’s one of those features that makes Ruby such a powerful dynamic language. An enumerator can be used to generate series like the Fibonacci series.

But when we do a .map / .each with a code block, then it would try to realize the enumerator fully and then apply the block over it.

That would be fine when we are working on something small like:

But when we take the above fib enumerator, which will grow into an infinite series, adding a .map would lead the code to an infinite loop. If you are crazy enough to write an infinite loop, …

Read More

Working with timezones in rails


Bookmark and Share

Ruby on Rails being an amazing framework, helps us manage the timezone of our rails application. It gives us access to a lot of helpers, to make our life easier. For example, if you want to change all the date and time of your application to the logged in users time zone, we just have to place the following code in the application_controller.

We assume that you have stored the user’s time_zone in your database in the time_zone column.

The application  to show  timezone can be set in your application.rb, if we don’t set a particular timezone then the application will just show the systems timezone.

If you want to know all the timezone options available in rails, run the rake -D time command in your terminal.

Even though rails would take care of the timezone, when we are using certain ruby commands, it gives us our systems timezone and not the one set by rails. So to avoid surprises, we should be aware of the timezones we are exposed to.

A rails app, would always be exposed to three timezones:

  • System timezone
  • Database timezone
  • Rails applications own timezone

All three could be different, for example your system timezone could be in …

Read More

Managing associated objects


Bookmark and Share

Most of the rails applications build, works around databases. And the most commonly used relationship in database is the one to many relationship. In rails its represented as has_many on the parent side and belong_to on the child’s side. Now, as we write the relationship we also need to make sure what should be done to the children when the parent is destroyed. Else we will be stuck with a lot of orphan records once the parent is destroyed.

So to avoid that, we pass in the dependent attribute at the parents side, like below:

has_many :users, dependent: :destroy

The above code will run the destroy method on the children, when the parent is destroyed.

Like destroy, rails provides a total of five options. They are

  • 1: destroy – run the destroy method on all the associated objects, there by also triggering the callbacks
  • 2: delete_all – causes the associated methods to be deleted directly from DB, no callbacks triggered. This would be a faster, compared to :destroy, to delete the associated models.
  • 3: nullify – sets the foreign key to be set to NULL. no callbacks triggered. We use it when we don’t want the children to be …
Read More

Database transaction in Rails


Bookmark and Share

A transaction is a sequence of operations performed as a single logical unit of work. A logical unit of work must exhibit four properties called the atomicity, consistency, isolation and durability (ACID) properties, to qualify as a transaction.

We use database transactions to make sure that all the instructions we send to database are successful, and would cause changes to the database only if they are successful. Let’s say that you are working on a banking application which would withdraw money from one account and deposit into another account. The code for it would look like below

But for some reason, the withdrawal was successful but the deposit was not, the amount was taken out but never deposited to the other user.To avoid these kind of issues, database has a functionality called transactions, in which you can  build up each sql query. But if for any reason, any of the sql statements fails or an exception rises in the block, all the transactions are rolled back to their original form.

In rails, the transaction method is available as class method and instance method, but the functionality for both is same. There is no difference when you will use.

and

The …

Read More

after_create vs after_save vs after_commit

after_save, after_create and after_commit are called active record call backs in rails. They get executed when we work on the database, similarly we also have before_* callback and callbacks on destroy as well. In this article I will explain you about the difference between *_save, *_create and *_commit callbacks.

The purpose of each as per rails docs:

after_create
Is called after Base.save on new objects that haven‘t been saved yet (no record exists)

after_save
Is called after Base.save (regardless of whether it‘s a create or update save)

after_commit
Is called after the database transaction is completed.

Now to explain the real difference between the three, we must first explain about database transaction. They are a protective block around a group of sql statements, that are permanent only if all of them succeed in a single atomic statement.

When rails execute a create, the after_save and after_create would be called within the transaction block of the create statement. So they will be executed before executing the sql statement to make permanent changes in the DB. If the query fails, then no change will happen to the DB, but we would have executed the instructions of the after_create and after_save block.

Where as after_commit, is called after the execution of the final/outer transaction block. Thus the changes in the DB would be permanent.

Read More

Enable log rotation within the rails application


Bookmark and Share

Any person who has worked with a rails application for a good amount of time would have faced the issue of log files growing and consuming the entire space in the hard disk. Although this sounds funny, it does happen if you do not place a log management for your rails app (in production). You can manage your logs using log rotation. Do note that log rotation is not required if you host your app in heroku, as heroku won’t let you store files for more than 15 minutes in their server. You also do not need it if you are using some third party services like loggly or papertrail to manage your logs .

In the unix world, you can use log rotate service, which would be installed by default in all linux servers. But we at Red Panthers feel that everything that touches or involves our rails application should be placed along with our rails application as much as possible. If you feel the same way, it can be achieved by placing the code below in the production.rb file.

The Logger.new accepts three parameters:

  • The file name, which would be production.log
  • The number of files you want to keep
  • The size of …
  • Read More

    Skip unnecessary files while running Rails Generate

    Rails Generate is one of the features provided by Rails that would speed up the application development. However, we won’t be needing all the files generated by rails when running the generate command.

    For example:

    rails generate controller Home Index new create,  would create the following set of files:

    before_altering_the_generator

    As one knows from experience, the helper; javascript and stylesheet files are not always used. In fact, most of the time, we would have a single stye.scss, and main.coffee that would take care of 95% of the total behaviour of our application. So, if we do not delete those files after generation, we would just end up with a lot of files in our system which would have no code throughout the life cycle of the program.

    Fortunately, rails gives us the ability to customize its own generators so that we can disable these files from being generated. Once we place the below code in the application.rb, it will stop the generation of these extra files.

    Now, when you run rails generate controller Home Index new create, you will get less files.

    after_altering_generators

    Read More

    God Class: Breaking Single Responsibility Principle

              “God object: In object-oriented programming, is an object that knows too much or                  does too much.” 

    – Source: Wikipedia

    God class in OOP doesn’t stand for a good thing; here it’s called an anti-pattern. In Object Oriented Programming, we create a new class to define the properties and capabilities of an object. It is using these objects that we build our system, mimicking how it would work in the real world.

    For example: Let’s assume that we are trying to build a software to manage the office of a school.

    In a typical school office, there would be different departments to handle different parts of the administration. For example, the Purchase department for the purchases, the Accounts department for the accounts, the Records department for the records, the HR department to manage the staff. When one department wants something from another department, it would ask that department for the information. As per protocol, it shouldn’t take the files from the other department without the staff or the department lending it.

    So, mimicking the real world would mean that we build one class for each department of the office. We should build a class called Accounting, and in that class we will write all the functions that the Accounts department does, and only what it does. We will not write the functions for the HR department in the account class. Keeping all the code for a particular function at a single place makes our code more efficient and cleaner. Now every time we want the Accounts department to do something, we will create an object of that class and pass the data we have to get the information we need.

    Note: In an actual …

    Read More