Rails | Avoiding race conditions while updating particular field in DB

It’s okay to make mistakes when you are up to building simple applications. But for mission critical applications like Banking/Payment Processors, you gotta be very careful and keep listening to seniors and experts in critical matters.

Lets say you are working on a feature to update the total amount deposited in a particular account. Simple code will do like

# just after amount is debited from payee's account
def credit_receiver_account(debited_amount)
  update_attribute :total_amount, total + debited_amount

What’s wrong with the code above?

Continue reading


Rails : Import CSV data to database

Actually there are various ways to achieve this. Firstly you can use the PostGreSQL’s copy command. Secondly you can choose to use Ruby to load data.

Using copy command in PG

Create your table:

CREATE TABLE zip_codes 
(ZIP char(5), LATITUDE double precision, LONGITUDE double precision, 
CITY varchar, STATE char(2), COUNTY varchar, ZIP_CLASS varchar);

Copy data from your CSV file to the table:

COPY zip_codes FROM '/path/to/csv/ZIP_CODES.txt' DELIMITER ',' CSV;

You can also specify the columns to read:

\copy zip_codes(ZIP,CITY,STATE) FROM '/path/to/csv/ZIP_CODES.txt' DELIMITER ',' CSV


Using Ruby

# == Schema Information
# Table name: vehicles
#  id         :integer          not null, primary key
#  fuelType   :string
#  make       :string
#  model      :string
#  range      :string
#  rangeCity  :string
#  year       :string
#  VClass     :string
#  cylinders  :string
#  displ      :string
#  created_at :datetime         not null
#  updated_at :datetime         not null

class Vehicle < ApplicationRecord
  def self.import!
    CSV.foreach(Rails.root.join('db/vehicles.csv'), headers: true) do |row|
      Vehicle.create! row.to_hash.slice('fuelType', 'make', 'model', 'range', 'rangeCity', 'year', 'VClass', 'cylinders', 'displ')
      print '.'.green
# lib/tasks/load_vehicle_data.rake
desc 'Loads data from db/vehicles.csv file to vehicles table'
task :load_vehicle_data => :environment do
  MyLogger.log('Starting to load the vehicle data from db/vehicles.csv ...')

  MyLogger.log('Done loading the vehicle data from db/vehicles.csv!')


If you choose to beautify the Log then you can use this

# app/models/concerns/my_logger.rb
module MyLogger
  def log(message, message_color: :green)
    puts '~'.yellow.bold * 100
    puts "DateTime: #{}"
    puts '~'.yellow.bold * 100
    puts message.try(message_color)
    puts '~'.yellow.bold * 100

  module_function :log

For colorful CGI I have used this code in initializers

# config/initializers/string_modifier.rb
class String
  def black; "\e[30m#{self}\e[0m" end
  def red; "\e[31m#{self}\e[0m" end
  def green; "\e[32m#{self}\e[0m" end
  def blue; "\e[34m#{self}\e[0m" end

  def bold; "\e[1m#{self}\e[22m" end
  def italic; "\e[3m#{self}\e[23m" end
  def underline; "\e[4m#{self}\e[24m" end
  def blink; "\e[5m#{self}\e[25m" end
  def reverse_color; "\e[7m#{self}\e[27m" end
# note: if you use awesome_print gem, these methods will be auto-included


Screenshot from 2017-02-09 09-30-49.png





Mock HTTP using VCR with RSpec | Mock Authy | Rails

Well, slower test suite is a nightmare both in your local machine and in your CI server. If your gem provider has built some Mocking APIs then its cool. But, no mocking API and you are writing Unit Test for your models and controller then beware, do not leave your app making HTTP requests everytime.

What to do?

If you cannot mock your library then mock the damn Internet. Simple enough! you can get going in a couple of minutes. Continue reading


Rails : Mass assignment with ids in seeds.rb | PG::UniqueViolation: ERROR

Looks like you can mass-assign records into ActiveRecord models without any problem like

                    { parent_id: 1, name: 'Computer Science', description: 'Readable via Electronic devices.' },
                    { parent_id: 1, name: 'Electronics' },
                    { parent_id: 1, name: 'Law' },
                    { parent_id: 1, name: 'Social' }

But you cannot do like Continue reading


Redux in a nut shell

What is Redux?

Redux is a predictable state container for JavaScript apps.

In this tutorial we will create an awesome Redux app in organized fashion. But at first we will create an app in single file, analyse it and break it down to more manageable chunks of components and organize it in a comprehensible dir-structure. Continue reading


Simply Deploy React.js App to Heroku

If you have read my another post about creating a ToDo app in react you are good to go; if not see this post.

You know that React App is a single page application containing only static assets. So, you only need to setup a mechanism to serve your static assets like CSS, JS, HTML, IMAGE, etc. files when clients ask for. Either you can use market leader HTTP servers like Apache, Nginx, etc or simple Express server that runs in Node.js.

Continue reading


React.js | Advanced Todo App from scratch for beginner | Bootstrap | In a nut shell


It is a good practice to follow community standards while developing softwares. It has some major pros like

  • Its easier to understand and debug/maintain software
  • quicker to get help when needed from community
  • It will lower development cost [Money and Time]

We will be taking the convention used by this project into consideration. react-slingshot


Make a dir called ‘todo‘ and initialize a node.js app. Continue reading