Rack::Attack – secure you rails app for the real world


Bookmark and Share

Are you worried about the security issues in your Rails app? The rack-attack gem, can help you. Rack::Attack is a rack middleware which provides security to our rails application. It allows us to safelist, blacklist, throttle and to track requests.

  • If the request matches any safelist, it is allowed.
  • If the request matches any blocklist, it is blocked.
  • If the request matches any throttle, a counter is incremented in the Rack::Attack.cache. If any throttle’s limit is exceeded, the request is blocked.
  • Otherwise, all tracks are checked, and the request is allowed.

Implementation

Install the rack-attack gem, or add it to you Gemfile as:

Then tell your app to use the Rack::Attack middleware. For Rails 3+ apps:

Or you can use it in Rackup file as

By default, Rack Attack uses Rails cache. You can override that by setting the Rack::Attack.cache.store value. It is used for throttling. If you want to create use a custom adapter, for example, memory store,  create a file called rack_attack.rb in config/initializers to configure Rack Attack and put the following code in the file:

Throttle

Here we are limiting the request per seconds from the same …

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 …

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 …

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 …

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 …

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

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 …

Read More