How to write your own Rack middleware


Bookmark and Share

How to write your own Rack middleware

Rack is a Ruby package which provides an interface for a web server to communicate with the application. It is very easy to add middleware components between the web server and the app to customize the way your request/response behaves. The middleware component sits between the client and the server, processing inbound requests and outbound responses. Rack Middleware is an implementation of the pipeline design pattern for web servers using Rack.

For example with Rack, we can have separate stages of the pipeline:

  • Authentication: Checks whether the login details are correct or not when the request arrives.
  • Authorization:  It performs role-based security. i.e. checks whether the user is authorized to perform the particular task.
  • Caching: Return a cached result if the request is already processed.
  • Decoration: Enhance the request to make downstream processing better.
  • Performance & Usage Monitoring: Status get from the request and response.
  • Execution: actually handle the request and provide a response.

Next, we will see how to build our own rack middleware.

Building your own …

Read More

Introduction to generating JSON using PostgreSQL


Bookmark and Share

Introduction

One of the major requirements for any online business is to have a backend that either provides or can be extended to provide an API response. Building  websites with static HTML and simple jquery ajax is coming to an end. In this era, Javascript frameworks rules the market. Hence, it is a good decision for the database to support JSON, as JSON is becoming the glue that connects the frontend and backend.

Rails have an inbuilt support for generating JSON, as it’s our swiss army knife of web development, and encourages the REST URL structure . And its a good choice for building API. It is good enough to a particular point of growth. Very soon you will reach bottlenecks, where you have more requests than you can handle and you have to either spawn up more servers or use some concurrent languages like elixir, go, etc. Before we go to that scale and burn down the existing codebase, we can use database to generate JSON responses for us, which is 10 times faster in generating JSON than Rails (though more verbose).

Since PostgreSQL 9.2, the database has taken a major leap in supporting JSON. The …

Read More

New binding.irb introduced in ruby 2.4


Bookmark and Share

Ruby 2.4 will have the feature to introduce a REPL session, using IRB, in between your code execution for better debugging. IRB, which stands for Interactive Ruby, is the standard REPL which is bundled along with ruby. Pry is a popular alternative for IRB, which has many developer-friendly features like tab compilation and syntax highlighting. One of the most heavily used features of pry is the ability to introduce a REPL session in between your code execution for better debugging. Instead of using p or puts to print the result and various variables, this helps us try out various codes and fixes in between the code to find the right solution.

binding.pry being used.

 

To use binding.irb in your code, you need to require the IRB library to your code and call binding.irb where you want to introduce the REPL.

and you will see a REPL like below.

screen-shot-2016-11-22-at-10-47-27-am

 

Read More

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

application_record.rb available since rails 5


Bookmark and Share

Those who have been starting with Rails 5, must have noticed the new application_record.rb file present in your model folder. And all new models seems to be inheriting the application_record.rb instead of the ActiveRecord::Base. This is done so that we don’t pollute the ActiveRecord::Base namespace with our own extensions.  Before when we require something, say an extension to the ActiveRecord itself we used to have it included using the following code.

Now the problem with this approach is that when we use rails engines this NewFeature gets added in there as well, and it could end up doing things that we didn’t expect.

With the new application_record.rb, which would be inherited by all the models, we need to include the new module at the ApplicationRecord and it would be available as the new feature of ActiveRecord. Every new engine generated using rails plugin new would also be having their own application_reocord.rb

One more point to note is that we can place application wide hooks in this file. So if you were to do

it would be triggered when a new record is created in any of the models of the rails application.

Read More

Optimising PostgreSQL database query using indexes


Bookmark and Share

At Red Panthers PostgreSQL is our go to database we use it everywhere. So thinking about how to optimize our database performance is one of the most talked about topic at our office. The best way to speed up report generation and data retrieval within a rails application is to leave it to the database, as they have algorithms and optimizations build just for that. We always felt that most Ruby on Rails projects out there, do not use the full potential of a database and they usually just limit it to a data store. PostgreSQL or any database for that matter is much more than that.

We would be blogging on how we use PostgreSQL in our projects to speed up our client’s applications. This particle is the first part of a series of article we would be writing on database optimization.

Database Indexes:

Indexes are a special lookup table that the database search engine can use to speed up data retrieval. An Index is similar to a pointer to a particular row of a table. As a real world example, consider a Britannica Encyclopedia with 22 volumes of books, and an extra book listing  the index,with which you can find out 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

    How to learn Ruby on Rails


    Bookmark and Share

    Well I have been hearing a lot from people in facebook, google groups and online forum wanting to learn Rails. Their question is simple “I want to learn Rails”, “How do I learn Ruby on Rails?”, “How do I become a Ruby on Rails programmer?”. Well the funny feeling I get while reading these questions is that, its the exact questions I posted in Google Groups, forums, etc when I wanted to start learning Rails and Ruby couple of years ago. So I thought of giving back to the community and to my company blog, by posting on how to learn rails, and answer a few questions every newbie always have.

    Q) How to learn Ruby on Rails?

    Well to get started, I would suggest this Rails Tutorial. Excellent tutorial, with detailed explanation. Build for people with little or no knowledge in Ruby. Further more it also teaches and introduces a newbie to Git and TDD.

    If you don’t like reading from the web, and prefer books then I suggest Agile Web Development With Rails by Sam Ruby, Dave Thomas, David Heinemeier Hansson. The advantage of using rails is the ability to become more …

    Read More