vendor-lockin-banner-1920x540-01

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
end

What’s wrong with the code above?

Continue reading

importdata

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
    end
  end
end
# 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 ...')
  
  Vehicle.import!

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

 

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: #{DateTime.now}"
    puts '~'.yellow.bold * 100
    puts message.try(message_color)
    puts '~'.yellow.bold * 100
  end

  module_function :log
end

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
end
# note: if you use awesome_print gem, these methods will be auto-included

 

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

 

Sources

http://stackoverflow.com/questions/2987433/how-to-import-csv-file-data-into-a-postgresql-table

 

cassette-tape-vectors

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

signs-not-to-be-a-programmer-sitting

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

Category.create([
                    { 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

react_best_practices-1453211146748

Getting started with React.Js using NPM

My assumptions: You have prior experience of Web framework like 
  Ruby on Rails, Django, Phoenix, etc. 
Please refer to this React.js style guide for community comprehensible source code.

Hey, its not mandatory to use NPM to build applications with ReactJs; but, it will be alot easier to build, maintain, share codes using NPM. Firstly you should have NodeJs installed in your development machine.

Installation for Development Environment

$ sudo apt-get install nodejs
# try 
$ node -v
# v4.2.6
# if its says command not found: node then try 
$ nodejs
# If it shows up, it means due no some name conflicts 
# the name/command node is already taken by some binary. 
# So, its get it back.
$ sudo update-alternatives --install /usr/bin/node node /usr/bin/nodejs 10

Probable Issues: NPM not found

Continue reading

organizing-your-small-business

Rails|Ransack|Geocoder – Sort data by distance

If your application connects local businesses to local customer, then you might have used Ransack for sorting and searching of records. For geocoding and reverse-geocoding, you might be using Geocoder gem. If you want to let users to sort results by distance then its pretty easy.

Things to remember,

  • If you use Model.near([lat, long]) method, Ransack adds a new column called distance to the ActiverecordRelation object. You can access the method distance by prying.

Continue reading

rating