Difference between Date, Time and DateTime

Bookmark and Share

Date and time are one of the most important aspects which every coder has to deal with in Ruby. Well, let’s get to know how we keep it up alive and functional.
There are 3 different classes in Ruby that handles date and time. They are Date, Time and DateTime. Date and DateTime classes are both from date library. And Time class from its own time library.

In this article we’ll see how Date and Time works. Let’s have a look at each one of them.


When you need a string format of year, month and day, you have to go through Date class.

  • Has date attributes only (year, month, day)
  • Based on integer whole-day intervals from an arbitrary “day zero”
  • Can handle date arithmetic in units of whole days
  • Date object is created with ::new, ::jd, ::ordinal, ::commercial, ::parse, ::strptime, ::today, Time#to_date etc.
  • Takes 4 bytes to store.



If you need both date and time values, we can make use of Time class.

  • Has date and time attributes (year, month, day, hour, min, sec, subsec)
  • Can handle negative times before unix time
  • Can handle time arithmetic in units of seconds


Also rails provide a really good time class called ActiveSupport::TimeWithZone. It contains all the features the Time

Read More

Enumerator: When to Use and Why are they so special?

Bookmark and Share

In this post, we’ll take a look at the basics of Enumerator, When to use it and Why they are so special. So let’s begin!

As the name implies Enumerator is used for iterating over a collection of items. It allows both internal and external iteration.

So how do we Create an Enumerator?

There are 3 different ways to create it. They are from,

  • A Block,
  • An Enumerable,
  • A Blockless Enumerable Method Call.

Let’s have a look on each of the method now.

From a Block

We can create an enum by passing a block to its constructor. A yielder object will be passed to this block. The yielder’s #<< method can be used to define the elements. Enumerator#next can then be used to provide iteration.


From an Enumerable

The most common way to create an Enumerator is from an Enumerable object, specifically, an object that defines a #each method. Object#to_enum is implemented to return a new Enumerator which will enumerate by sending #each to its receiver.


From a Blockless Enumerable Method Call

There are several Enumerable methods that take a block and returns an Enumerator when called without a block. For instance, calling Array#select without a block will return an Enumerator with an #each method that will filter like #select.These blockless calls …

Read More

ReactJS for Beginners | A Step by Step Approach

Bookmark and Share

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 …

Read More

PStore, a little known feature in the standard library

Bookmark and Share

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 …

Read More

How to write your own Rack middleware

Bookmark and Share

How to write your own Rack middleware

Rack is a Ruby package which provides an interface for a web server to communicate with the application. It is very easy to add middleware components between the web server and the app to customize the way your request/response behaves. The middleware component sits between the client and the server, processing inbound requests and outbound responses. Rack Middleware is an implementation of the pipeline design pattern for web servers using Rack.

For example with Rack, we can have separate stages of the pipeline:

  • Authentication: Checks whether the login details are correct or not when the request arrives.
  • Authorization:  It performs role-based security. i.e. checks whether the user is authorized to perform the particular task.
  • Caching: Return a cached result if the request is already processed.
  • Decoration: Enhance the request to make downstream processing better.
  • Performance & Usage Monitoring: Status get from the request and response.
  • Execution: actually handle the request and provide a response.

Next, we will see how to build our own rack middleware.

Building your own …

Read More

Using gmail to send email in Ruby on Rails

Bookmark and Share

Emails can be sent from you Rails application through many services like mandril, sendgrid, amazon SES. In this article, we would be explaining how we can send email using a Gmail credentials. Even though we can’t use it in production scenario due to the 500 email per day limitation, it would help us in prototyping an application quickly and also for cases where you want to send actual email in your development environment. Action Mailer is the ruby library in rails that will help us to do this.

Action Mailer allows you to send emails from your application using mailer classes and views. Mailers work very similarly to controllers. They inherit from ActionMailer::Base and live in app/mailers, and they have associated views that appear in app/views.To setup action mailer, must do the following:

1. Configuring the mailer in your environment file
2. Generating the mailer
3. Defining mailer action
4. Generating the mailer view
5. Delivering the email

Action Mailer Configuration

To configure action mailer add the following to your appropriate config/environments/$RAILS_ENV.rb file:


Generating the mailer

As you generate a controller for your application, you can …

Read More

Different ways to run Shell Commands in Ruby

Bookmark and Share

During development of an application, there will come cases when we need to access system command from our program itself. In some cases we just need to know if the status was complete, in some cases, we also need to know the output the application returns.But before we start, let’s find out what Shell Commands are. Simply put, the shell is a program that takes your commands from the keyboard and gives them to the operating system to perform. There are several additional shell programs available on a typical Linux system. Described below are 6 different way to execute a shell script from ruby and their properties.

  • Exec
  • System
  • Backticks ()
  • IO#popen
  • open3#popen3
  • open4#popen4
  • Exec

    Kernel#exec (or simply exec) replaces the current process by running the given command, which can take one of the following forms:

    command line string which is passed to the standard shell

    exec(cmdname, arg1, …)
    command name and one or more arguments (no shell)

    exec([cmdname, argv0], arg1, …)
    command name, argv and zero or more arguments (no shell)

    In the first form, the string is taken as a command line that is subject to shell expansion before being executed.

    In the second form (exec(“command1”, “arg1”, …)), the first is taken …

    Read More

    New binding.irb introduced in ruby 2.4

    Bookmark and Share

    Ruby 2.4 will have the feature to introduce a REPL session, using IRB, in between your code execution for better debugging. IRB, which stands for Interactive Ruby, is the standard REPL which is bundled along with ruby. Pry is a popular alternative for IRB, which has many developer-friendly features like tab compilation and syntax highlighting. One of the most heavily used features of pry is the ability to introduce a REPL session in between your code execution for better debugging. Instead of using p or puts to print the result and various variables, this helps us try out various codes and fixes in between the code to find the right solution.

    binding.pry being used.


    To use binding.irb in your code, you need to require the IRB library to your code and call binding.irb where you want to introduce the REPL.

    and you will see a REPL like below.



    Read More

    Different types of Index in PostgreSQL

    Bookmark and Share

    This is part two of our PostgreSQL optimization series. You can read the first article where we discuss when to index here.

    PostgreSQL uses a different set of algorithm while indexing tables, each type of algorithm is good for a certain set of data. Here we will be discussing the various algorithms available and when we should be using them. (Note these are the algorithms found in PostgreSQL 9.5)


    B-Tree (Balance Tree), is the default algorithm used when we build indexes in Rails. It keeps a sorted copy of our column, which would be our index. So if we want to find the row of the word starting with a then as soon as the words starting with a are over. It will stop searching and return null, as the index has kept everything sorted. It is good in most cases, hence it is the default algorithm used.

    Hash is one of the most popular indexing algorithms. But only the equate operator works on it, thus the query planner will only use an index with a hash algorithm if we do an equal operation searching for it. Another point to note is that Hash index …

    Read More

    How to write maintainable routes in rails

    Bookmark and Share

    config/routes.rb is the gateway to your ruby on rails application. All request send by your users are directed to the appropriate code by the routes.


    When someone visits your-website.com/profiles then the request is taken to the Index action of the UsersController. Under that action you will get the index.html.erb. So using routes we have configured the UsersController to respond to the users request it is its responsibility to do it now.

    We can declare routes in various ways:

    Since there are multiple ways to declare routes (as all forms are right), its best to stick with a single method for the code to be more readable. routes.rb is going to be one of the most heavily edited file in your project as when ever you add a new page or create a new form, you need to add a route to access the page or an end-point to accept the request. So it is most likely that your routes.rb file will start to grow ugly:

    So here we will share some tips to write proper, maintainable routes:

    First important point to note is that, its best to write routes as resources


    declaring resources will create the following 7 routes.

    Read More