All blog articles by Varun Lalan

ActiveAdmin is great framework for managing website administration interfaces. It allows us to list records of a table, filter them, sort them and also support exporting them in CSV, XML or JSON. By default, records that are being displayed are exported. For example, say we have a products table where each product is distinguished by their type. We can apply a filter to list all electronics products. Clicking on CSV link below the list will export all electronics products only.

But sometimes…

Read complete blog post

In one of our Rails 4 app, we decided to move file and image uploads to another microservice so that the load on server is reduced when a big file is uploaded. We decided to do this in Phoenix.

In Phoenix, we have ex_aws package which makes file uploads to S3 very simple just like Rails. So lets get started.

Add ex_aws

Update mix.exs to include following dependencies.

defp deps do
    {:ex_aws, "~> 1.0"},
    {:poison, "~> 2.0"},
    {:hackney, "~> 1.6"},
    {:sweet_xml, "~>

Read complete blog post

Recently we improved performance of one of our Ruby on Rails application. We used NewRelic tool to identify areas that were slow. One of which was file and image uploads to S3 from a text editor (Redactor).

When a user uploads a big file or image - the app's server response time shoots up degrading the performance and overall throughput because the files and images were being uploaded via rails action. The server process was busy uploading file on S3 while other requests to server were being…

Read complete blog post

Varun Lalan

String encoding is something that we don't really think until we see

     Encoding::CompatibilityError: incompatible character encodings: UTF-8 and ASCII-8BIT 

Or when users complains about missing special characters like "" (apostrophe copied from Microsoft Word) or when "菜医生" becomes "иЏњеЊ»з”џ".

Before we go into encoding problems, lets understand what encoding is.

A string can be considered as an array of bytes:

irb(main):001:0> "world".bytes
=> [119, 111, 114, 108, 100]

Here 119 me…

Read complete blog post

Varun Lalan

In one of our Rails application, we needed to generate password protected PDFs. We used wicked_pdf (an awesome gem that generates PDFs from HTML template) to generate PDFs but it doesn't provide feature to secure it.

While searching for solution to secure PDFs we came across PDFtk (PDF toolkit). It is a cross-platform tool for manipulating PDF documents. It has feature to add password to PDF document using "user password" as well as "master password" (owner password) which is great.

Read complete blog post

By default, regular expression matching is greedy, which means they try to match as many matches as possible in a given string.

Lets see an example considering HTML snippet - <p>Hello</p><span>Awesome</span><p>World</p>. Our task is to extract first p tag. i.e pattern matching should return <p>Hello</p>.

Immediate solution is to write regex - /<p>.*<\/p>/. But it would match the whole string.


The reason it matches whole string is because * (and also +) is greedy. That is, the star…

Read complete blog post

Almost all Ruby on Rails developers might come across scenario where they need to add a new column with a default value to one of the database tables. Most of us (including me) would write following migration statement -

add_column :table_name, :column_name, :boolean, default: false

This is a good practice but would cause downtime if the table has large number of records. It took 3 secs when I ran the migration for a table having 50k records.

-- add_column(:table_name, :column_name,

Read complete blog post

Sometimes you’ll want to refer to your image assets from inside of your JavaScript or CoffeeScript files. We have nice rails helpers that would allow us to do so but we need to append .erb to every .js or .coffee file we want to reference images.

I didn’t like it that way, because ERB inside of CoffeeScript looks odd and having the file end with .erb messes up syntax highlighting.

A way around this is by adding following piece of code (not the beautiful one) to one single file that ends on .er

Read complete blog post

Cordova File Transfer plugin allows you to transfer / upload photos from mobile to server. You generally need a file with path for transferring / uploading files via File Transfer plugin.

More information on how to use Cordova File transfer plugin can be found here.

This plugin won't help much when we have a Base64 image (usually a drawing or signature drawn on canvas). To upload such images we can do:

  1. take your base64.
  2. write it to a file.
  3. then just use file transfer plugin to upload it to…

Read complete blog post

Varun Lalan

Active Admin is a great plugin that helps us to get administration functions with elegant and simple interface up and live quickly without much of a hassle or efforts. One can also make use of various customisations as per their need with very little effort.

In this article, I will be explaining how we can add custom search bar in Active Admin. Adding custom search bar is not as easy and straight forward as other Active Admin customisations. I will be making use of jQuery to do this.

Here, I…

Read complete blog post

Varun Lalan

Sometimes we need to show different text based on some count. Like for example:

if box_count == 0
  message = "No boxes present"
elsif box_count == 1
  message = "Only 1 box present"
  message = "There are #{box_count} boxes"

You can refactor this to make use of i18n locales power. In en.yml you can do -

      zero: No boxes present
      one: Only 1 box present
      other: There are %{count} boxes

And in view we can use: <%= t('boxes.message', count: 2)

Read complete blog post

Varun Lalan

In one of the feature, we had to import xlsx which was exported from sqlite database dump. The rows had few image names which was uploaded to sftp server. We had to upload those to images on S3.

Importing xlsx row data was simple but the challenge was how to upload images from sftp server to S3. This is where net-sftp gem came to our rescue (though its not managed anymore).

To get this working, we need 4 things: host, username and password using which we are going to login to sftp server and p

Read complete blog post

Many times websites get hit by unreliable sources which can mainly be automated scripts that continuously hits a web url which can cause DOS(Denial of Service) attack.

In Rails, we are handle such types of attacks by restricting the requests at Rack level. Rack is a middleware which can serve as "a way to filter a request and response".

For this, we can use rack-attack.


Rack::Attack.blacklist('allow2ban rapid send_verification_code') do |req|
  if && req.path ==

Read complete blog post

Varun Lalan

Rails 3.1 and above has an awesome feature of prepared_statements. The basic idea behind prepared statements is to compile SQL statements once and cached for it future use. In other words - The benefit to prepared statements is that the database does not have to compile a query plan for every piece of SQL sent to it, potentially saving a lot of time.

Checkout an excellent blog(blog) to know more on prepared_statements.

Recently, I had to get raw sql from AR object so that I can pass it to…

Read complete blog post

Varun Lalan

Recently I added few integration tests in my projects using Capybara and Selenium webdriver and ran into banging my head against inconsistencies with test database. I create some records in test DB which were completely invisible to Selenium-driven browser-based tests.

The problem is: the tests are being wrapped in database transactions, so any code running outside the actual test process (like, say, a server process servicing a Selenium-driven browser request) does not see the database…

Read complete blog post

Varun Lalan

For displaying flash messages and other informative messages, we generally use Internationalization (I18n) in rails.

Sometimes we also need to write similar messages again in javascript/coffeescripts which can be difficult to manage if these message changes. And also it doesnt follow the concept of DRY.

To follow DRY, we need to make rails locales available in javascript.

One way to do it is to declare a global variable and have all locales saved to it as Javascript Object.

This is what we…

Read complete blog post

Varun Lalan

Please find attached pdf file for Coding Standards.

Also, refer following git repo for all Ruby idoms:

Gem you should consider for refactoring and code formatting:

  1. rubocop

  2. cane

  3. rails_best_practices

For code complexity use flog gem. Refer post here for more details.

Happy Refactoring :)

Read complete blog post

Varun Lalan

In most of our apps, we probably need to execute few background tasks more often, like every 10 minutes, once a week, etc. For scheduling these jobs, we need a scheduler that can re-run these tasks on specified intervals.

There are few schedulers like whenever, resque-scheduler, rufus-scheduler, etc that can do the job. However, these gems are not compatible Sidekiq and with apps deployed on Heroku.

There are 2 ways to make it work on Heroku.

1/ Using Heroku Scheduler addon.



Read complete blog post

In one of our eCommerce app, we needed SEO friendly Menu urls like /brandy/cognac. For this, we added a generic route /:parent/:child/:grandchild at the bottom of config/routes.rb.

With this approach, there was an issue with invalid urls like /this/is/wrong being redirected to specified controller action.

To fix this, we used Menu names to generate specific urls. But the routes would become invalid if Admin changes the menu name.

So we needed a way to reload routes once the menu is updated.

Read complete blog post

Code Climate is a great web-tool to check code complexity, duplications and security vulnerabilities. Internally, code climate uses Flog to calculate code complexity and BrakeMan for security vulnerabilities. But it checks only when we commit code to Git.

We can check code complexity and security issues before committing to git.

For code complexity:

1) install flog

gem install flog

2) Goto project root path and run command:

find path_of_file -name *.rb | xargs flog

For example…

Read complete blog post