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

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.


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:


Here we are limiting the request per seconds from the same IP address. Here we are limiting only 3 requests in 10 sec.


Above example always allows the request from localhost. And the request is allowed if the value is true.


Here, it blocks the request from ‘’.

Fail2Ban: Fail2Ban.filter can be used within a blocklist to block all requests from misbehaving clients.

Allow2Ban: Allow2Ban.filter works the same way as the Fail2Ban.filter except that it allows requests from misbehaving clients until such time as they reach maximum retry.

Block logins from a bad user agent

In the above example, if a bad user tries to login, the request is blocked.


It tracks request from a special user.

Security issues that Rack Attack addresses

  • Rate limits against DDoS and abusive users

DDoS is short for Distributed …

Read More

ReactJS for Beginners | A Step by Step Approach

There are many problems while building large applications with data that changes over time. To solve this ,I suggest checking out ReactJS. React lets you express how your app should look at any given point, and can automatically manage all UI updates when your underlying data changes.

React is one of the most popular JavaScript front end libraries which is developed by Facebook. It’s used for handling view layer for web and mobile apps. The main feature of ReactJS is that it allows us to create reusable UI components.  The syntax used in React is JSX which allows you to mix HTML with JavaScript. This is not a requirement – you can still write in plain JavaScript. But this is suggested because this makes writing your components a breeze.


To install React with Yarn, run:

To install React with npm, run:

The bundlers like webpack or Browserify is recommended. So you can write modular code and bundle it together into small packages to optimize load time.

Use React with Babel to let you use ES6 and JSX in your JavaScript code. ES6 is a set of modern JavaScript features that make development easier.  JSX is an extension to the JavaScript language that works nicely with ReactJS.

React is efficient

ReactJS creates its own virtual DOM where your components actually live. It calculates what changes need to be made in the DOM beforehand and updates the DOM tree accordingly. So it is flexible and gives amazing gains in performance. It can be used on client and server side. This way, React avoids costly DOM operations and makes updates in a very efficient manner.

The smallest ReactJS example …

Read More

Fixtures in Rails Tests

Fixtures  are one of the important thing in Rails testing. Testing the application helps to debug it more efficiently and ensures the desired functionality to the application. Let’s have a look on them.

It is used to manage the test data. It tests against the real data and is written in YAML files. For each model in the application, there is a .yml file in the test/fixtures directory. When we generate the model using rails g it will automatically create the .yml file also. Here you can see an example,

Here ‘Matz’ is the fixture name. And the name and message are the fields in the User model.

Fixtures come in 3 flavours:

  • YAML fixtures: It is a file format which describes data structures in human-readable format.These are stored in a single file per model(above example is in yaml format).
  • CSV fixtures: Here values are kept in the Comma Separated Value (CSV) format. These are stored in a single file but instead end with the .csv file extension.


  • Single-file fixtures: These are the original format for Active Record.


Creating multiple/random items in fixtures

You can create multiple items as:

When you add fixtures, they get IDs based on a hash of the table name and the fixture name. To us humans, they just look like random numbers. So there is no need to define the id for this. It will ensure that the id is unique for every item.

Fixtures are unordered. If you want ordered items, use the omap YAML type. Also, you can access the data in the test as:

Where ‘users’ is the name of the yml file and ‘Adorn’ is the fixture name.

ERB Fixtures

You can add ERB with your YAML fixtures to create a bunch of fixtures as:

In the above example, the code generate 1000 users.

Writing belongs_to/has_many relationships

We can also define associations between fixtures. …

Read More

Spice up your boring IRB (Irbtools)

IRB stands for interactive ruby, it is a tool for interactively executing ruby expressions read from a standard input. To invoke it, type irb at the shell or command prompt, and begin entering Ruby statements and expressions. But it has some limitations. A solution to this is called ‘irbtools‘, which make using irb easier and more fun. It improves Ruby’s irb console like colored output and lots of helpful methods.


Install the gem by using:


Add it to your project’s Gemfile:


IRB executes code in ~/.irbrc on start-up.To use irbtools, put the following code in ~/.irbrc file:

We can start IRB directly from the code by calling,

When installing irbtools, some gems will not be installed. For example, the bond gem for better auto-completion. These are packaged as irbtools-more (requires ruby version >= 2.4). To use irbtools-more, change the .irbrc to:

and edit Gemfile as

For example, the output looks like:



  • Colorized and output as comment by wirb and fancy_irb
  • Nice IRB prompt and IRB’s auto indention
  • Includes stdlib’s FileUtils: ls, cd, pwd, ln_s, rm, mkdir, touch, cat
  • Many debugging helpers:
    • ap – awesome_print
    • q –like p, but on one line
    • Object#m – ordered method list (takes integer parameter: level of nesting)
    • Objedt#d – puts the object, returns self (using tap)
  • “Magical” information constants: Info, OS, RubyVersion, RubyEngine
    • OS.windows?
    • RubyEngine.jruby?
    • RubyVersion.is.at_least? 1.9
  • Clipboard features: copy and paste
  • Call vim to edit a file, close it and it gets loaded into your current irb session, powered by interactive_editor
  • Highlight a string with colorize(‘string’) or a file with ray(‘path’), powered by coderay
  • Displays ActiveRecord database entries as tables with …
  • Read More

    PStore, a little known feature in the standard library

    PStore(persistent store) implements a file based persistence mechanism based on a Hash. It writes Ruby objects to an external file so it can access easily if needed. If an I/O error occurs while PStore is writing to its file, then the file will become corrupted.You can prevent this by setting pstore.ultra_safe = true. Also, it supports thread-safe and uses Marshal internally.

    To use this library, you must require it and instantiate a new object.

    Which would create a file that stores the content to be written.

    To store or retrieve data from the data store, you must open a transaction. Here transaction is a protective wrapper around SQL statements to ensure changes to the database only occur when all actions succeed together. We can access the content of database only through this transaction.

    At the end of the transaction, all changes are committed.

    Public Instance methods

    Instance methods are methods that are called on an instance of a class. We can use the below methods while using PStore instances.

    • p[name]=obj

    Stores obj in the database under the key name. When the transaction is completed, all objects accessed reflexively by obj  are saved in a file.

    • p.root?(name)

    Returns true if the key name exists in the database.

    • p.commit

    Complete the transaction. When this method is called, the block passed to the transaction method is executed, and changes to the database are written to the database file.

    • p.abort

    Aborts the transaction. When this method is called, the execution of the block passed to the transaction method is terminated, and changes made to database objects during the transaction aren’t written to the database file.

    Let’s walk through a simple example. Below shows storing employee data into a simple PStore database. The file looks like:


    In the above example, to use the library we …

    Read More

    Disabling transaction block during migration

    Migrations are used to modify your database. By default, all migrations run inside a transaction. You can disable the transaction during migration. Let’s have a look on how to disable transaction block!

    Migrations can manage the evolution of a schema used by several physical databases. It’s a solution to the common problem of adding a field to make a new feature work in your local database, but being unsure of how to push that change to other developers and to the production server. With migrations, you can describe the transformations in self-contained classes that can be checked into version control systems and executed against another database that might be one, two, or five versions behind.

    In Rails, transactions are protective blocks around SQL statements that ensure changes to the database only occur when all actions succeed together. Transactions enforce the integrity of the database and guard the data against program errors or database break-downs. So basically you should use transaction block whenever you have a number of statements that must be executed together or not at all.



    DDL can’t run inside a transaction block. You can disable DDL transactions in Rails, using disable_ddl_transaction. It is used in AR(Active Record) migrations to prevent your migration from being wrapped in a transaction. The name is misleading because your entire migration will have transactions disabled, not just for DDL SQL statements.

    Normally, Postgress locks writing while creating an index on it. It may take a longer time to complete. However, PostgreSQL supports adding/dropping indexes concurrently. When this option is used, PostgreSQL must perform two scans of the table, and in addition, it must wait for all existing transactions that could potentially modify or use the index to terminate. So the migration must not be run inside a transaction. For that, use disable_ddl_tranaction! to run that on outside.


    Postgres has a …

    Read More
    Behind the scenes of hash table performance in ruby 2.4

    Behind the scenes of hash table performance in ruby 2.4

    Ruby 2.4 got released this Christmas with a lot of exciting features. One of the most underrated features in ruby 2.4 is hash table improvements. Before going into details about implementation, let’s first check the benchmark to know how this change gonna affect your ruby application.

    Some benchmarks are:

    Getting keys and values of a hash


    Ruby 2.3.3


    ruby 2.4.0

    Yeah, the above two operations executed ~ 3 times faster on my laptop. Though these numbers can vary with your machine and processor, the performance improvements will be significant on all modern processors. Not all operations became 3 times faster , average perfomence improvement is more than 50%

    If you are a ruby developer and excited to know what are the new features in ruby 2.4, then this feature gonna make your application faster and you don’t have to change anything in the code for that. Because these changes are backward compatible. If you are curious to know what happened behind the scenes of this performance boost, then continue reading.

    Hash Table

    In computing, hash table (hash map) is a data structure that is used to implement an associative array, a structure that can map keys to values. Hash table uses a hash function to compute an index into an array of buckets or slots, from which the desired value can be found. Wikipedia

    In other words, it is a data structure that allows you to store key value pair and helps to fetch specific data using the key in an efficient way. Unlike arrays, you don’t have to iterate through all elements to find a given element in the hash. If you are new to this data structure, check this cs50 video for a better understanding.

    That is cool right! Now, let’s see how this …

    Read More

    How to format Git log for meaningful information

    Git is a wonderful piece of software that makes life easier and more productive for a programmer. But sadly most developers don’t use it up to their full potential so we are going to blog about various simple and advanced usages of git as a series. In the first article of the series, we are going to talk about git logs.

    Git log is a great feature, that allows us to keep track of our works. There are different options available under git log command, which help us to customize the output of git log and also to filter the log.

    Git Graphs

    The –graph option draws a graph representing the branches and its structure of commit history. –oneline is used to display commit message and its hash in a single line, which is used along with –decorate, which helps us to easily see which commit belongs to which branch.

    Custom formatting

    This lets you display each commit however you want in printf style. For example %cn,  %h and %cd which represents committer name, abbreviated hash and committer date respectively.

    Filtering the output

    Git log can be filtered by different filters and format output

    By amount

    It displays latest n commits and its output.

    For example

    Will display latest 3 commit details

    By date

    Using –after and –before,  we can get logs after or before the specified date. You can also use these both to get logs between two dates


    –since and and –until are synonym for –after and –before

    –date flag is used to format the output of the date. There are different option available for –date flag such as short, iso8601, relative, etc…

    By Author

    When you are only looking for commits by certain user you can –author flag. You can also use regular expressions for this.

    By message

    When you want to search for log with certain string using –grep flag. You …

    Read More
    Kochi : Truly the Queen of the Arabian Sea

    Kochi : Truly the Queen of the Arabian Sea

    Before you set afoot on the land known as the “God’s Own Country”, you can see lush greenery covering up the suburb developed structures and providing that much needed fresh air to breathe. Kochi is a coastal city built on the ethos of communal integrity, cultural unity & truly to love nature. While under the colonial rule of the British Empire, they had laid the foundation on which Kochi is standing today.

    Kochi is the Business Capital of Kerala and home to more than 2.1 million people. It is a rapidly developing metropolitan city and is one of the selected cities to be developed as a Smart City under the Smart Cities Mission of Government of India.

    It also home to Kerala’s ever growing IT/ITES Industry, Infopark – an IT park developed by the Government of Kerala. Recently, World Trade Center opened its splendid office spaces here. Special Economic Zone for hardware manufacturing, Oil Refinery with a capacity of refining 9.5 million metric tons per annum to name few achievements. Kochi has a sprawling blend of industries.

    While you are at Cochin a.k.a Kochi to attend Ruby Conf India 2017 we just felt it would be really good to let you know about the must to visit, must to eat places around here. Being proud sponsors of Rubyconf2017 we believe it’s our duty to treat our guests in the best possible manner and this article is a small step to make your overall Rubyconf2017 experience pleasant and bliss.

    This is a curated list which we have jotted down from our experience here and we truly recommend each one of you adding one of the places to your itinerary. After all coming down to God’s Own Country it is very much necessary that you travel around to experience the cultural extravaganza of this unique city.

    • Fort …

    Read More

    Chartkick: data visualization made easy with Ruby

    Recently, I’ve been using Highcharts, Google charts and Chart Js for visualizing dynamic data in my projects. But it was difficult to integrate it with the rails application. However, for every problem in Ruby, there is a gem out there to save your day and Chartkick, a Ruby gem exclusively available for data visualization is truly a savior. Chartkick can work with Highcharts, Chart.js and Google charts to create dynamic and interactive charts that draw data from the Rails application. And the best part, you just need to write one single line of Ruby code. Isn’t that amazing and powerful!

    Let’s begin with Installation

    For installation, all you have to do is adding this line to your application’s Gemfile:

    Then you have to choose your charting library.
    In case, if more than one charting library is loaded, choose between them with the following code:

    P.S:- highcharts is the default adapter is nothing else is defined.

    Using Chartkick

    Once it’s installed, you can start playing around with chartkick. For example:

    In the above example, I have just shown you how we can make a line chart.Similarly, you can create Pie chart, Column chart, Bar chart, Area chart, Scatter chart, Geo charts, Timeline(Google Charts)etc. All you need is that one line of Ruby code. Cool, isn’t it!!

    Chartkick gives you a variety of options to make your charts interesting. You can also set a Global option for each chart by using initializers and even customize the HTML. Data can be passed as a Hash or as an Array. You can find more details about using Chartkick options, sending data in Chartkick documentation.

    Now, let’s have some real fun by using Chartkick to create some interactive Graphs, using Dynamic data.

    To create a graph which drives data from the ajax request, you just need to define a method …

    Read More