Crystal tuples: the immutable data structure of crystal

Tuple is a data structure which has immutable elements and is of a fixed size. Its similar to an array, but unlike arrays in crystal and ruby which allows adding more values over time a tuple is of fixed and cannot change. (Disclaimer: This article is meant for Ruby developer and explaining what a tuple is to a ruby developer).

In crystal we have two types of tuple

1) Tuple {1, “hello”, :world}
2) NamedTuple {x: 1, y:2, z: 5}

They are immutable, which means if you try changing the value of an element in a tuple you will get an exception. Since crystal programs are compiled before execution you will get to see these errors while you compile the program itself.


If you try assigning a value to it, like so

You will get an exception like bellow.

In crsytal, tuples are the preferred way to return a multiple results from a method.

For example inside the crystal core we have a method to get the minimum and maximum of an array.

the result would be {1, 100}

Note: Since we just mentioned minmax, have a look at minmax_by method as well. It would let you apply a block of code over your range and then return the minimum and maximum based on the returned collection.

Advantage of using tuple to return results instead of something like hash, is that we can be sure that our result cannot be altered accidentally. (since the data structure is immutable) 😁

You can build a tuple from an array by using the .from method

As a developer, the place where we use tuple the most in crystal are with splats(symbol: *). Passing arguments to method using splat and double splat operator is something we use widely in ruby keep our code small and readable. So if you wish to do the same in crystal you need to make a tuple …

Read More

Getting started with Faraday gem


Client libraries help in reducing the amount of code for the application developer who is using the API, whether a REST API or any other. By adding a set of code to the application, it provides the basic things an application needs to do in order to interact with the API. This is what a client library does. Also, it may handle user authentication and authorization.

Client libraries are developed by API developer or the community.

There are several HTTP client libraries in Ruby such as:

Among them, the favorite of mine is Faraday gem. Faraday has adapters for popular libraries like Net::HTTP. It is simple, flexible and supports multiple backends and embraces the concept of Rack middleware when processing the request/response cycle. Also, it’s possible to customize its behavior with middleware.

We will use a connection object to start with Faraday as it’s more flexible way than a simple getrequest.

Using this connection object, we make HTTP requests.

This will POST  title = ‘Faraday gem’  and created by = ‘blog’ to http://localhost:3000/tasks.

All HTTP verb methods can take an optional block that will yield aFaraday::Request object.


Basic and Token authentication are handled by Faraday::Request::BasicAuthentication and Faraday::Request::TokenAuthentication respectively. These can be added as middleware manually or through the helper methods.


To specify an HTTP proxy:

Using a different HTTP Adapter

Faraday provides an interface between our code and adapter. Sometimes we may want to use features that are not covered in Faraday’s interface. In such cases, we can have access to features specific to any of the adapters supported by Faraday, by passing a block when specifying the adapter to customize it.

For example, you can switch to the HTTPClient adapter as below

Like this, we can switch to any of the supported adapters.

The block parameters will change based on the adapters we are using.

Faraday::Connection object middlewares

A Faraday::Connection object has a list …

Read More

Getting start with React Native

React Native lets you build mobile apps using only JavaScript. A React Native app is a real mobile app. It uses the same design as React, letting you compose a rich mobile UI from declarative components.


Using Create React Native App we can start building a new React Native application easily. It allows you to start a project without installing or configuring any tools to build native code – no Xcode or Android Studio installation required.

Assuming that you have Node installed, you can use npm to install the create-react-native-app command-line utility:

Try creating a new project:-

This will start a development server for you, and print a QR code in your terminal.

To run your app,

Install the Expo client app on your iOS or Android phone and connect to the same wireless network as your computer. Using the Expo app, scan the QR code from your terminal to open your project.

Basic App

In the App.js file you can see:-

import, from, class, extends, and the () => syntax in the example above are all ES2015 (also known as ES6)  features. The unusual thing in this code example is.<Text>Hello world!</Text> This is JSX – a syntax for embedding XML within JavaScript. <Text> is a built-in component that just displays some text. This code is defining, App a new Component . Anything you see on the screen is some sort of component. A component can be pretty simple – the only thing that’s required is a render function which returns some JSX to render.

You can also write style in App.js file.

To modify your app, you can edit App.js file. The application should reload automatically once you save your changes.

Create React Native App

Create React Native App makes it really easy to run your React Native app on a physical device without setting up a development environment. If you want to run your app on the iOS Simulator or an Android Virtual Device, please refer to the instructions for building projects …

Read More

Observer Design Pattern in Ruby

Observer design pattern (also known as Publish/Subscribe) is a software design pattern, used when we are building a system where the state of one object affects the state of other objects. It is a key part of model-view-controller architectural pattern.

In a traditional MVC ( Model-View-Controller ) architecture, a model is a subject and a view is an observer. A view is notified when a model changes and responds accordingly. When the subject sends observers detailed information about what has changed, indiscriminately, this is known as the push model of the Observer pattern. When a subject sends only minimal information to its observers must ask for details explicitly, this is known as the pull model of the Observer pattern.

Observer Design Pattern

Ruby provides a simple mechanism to implement this design pattern using the Observable module. In this mechanism, the Notifier class uses the Observable module, which provides the methods for managing the associated observer objects.

The observable object must:

  • assert that it has #changed
  • call #notify_observers

An observer subscribes to updates using #add_observer, which also specifies the method called via notify observers. The default method for notify observers is update.

Public Instance Methods

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

  • add_observer(observer, func=:update)

Adds observer as an observer on this object, so that it will receive notifications.

  • changed(state=true)

Set the changed state of this object. Notifications will be sent only if the changed state is true.

  • changed?()

Returns true if this object’s state has been changed since the last notify_observers call.

  • count_observers()

Return the number of observers associated with this object.

  • delete_observer(observer)

Remove observer as an observer on this object so that it will no longer receive …

Read More


Gulp is a toolkit for automating painful or time-consuming tasks in your development workflow, so you can stop messing around and build something. You can compile sass files, uglify and compress js files and much more.


Make sure that you’ve installed Node and npm before attempting to install gulp.

Install the gulp command

Make sure that you have your package.json created by manually creating it or typing npm init.

Run this command in your project directory:

Create a gulpfile

In your project directory, create a file named gulpfile.js in your project root with these contents:

The first step to using Gulp is to require it in the gulpfile. Then you can begin to write a gulp task with this gulp variable. task-name refers to the name of the task, which would be used whenever you want to run a task in Gulp. You can also run the same task in the command line by writing gulp task-name.

Run the gulp command in your project directory:

To run multiple tasks, you can use gulp <task> <othertask>

Gulp tasks are usually a bit more complex than this. It usually contains two additional Gulp methods, plus a variety of Gulp plugins.

gulp.src tells the Gulp task what files to use for the task, while gulp.desttells Gulp where to output the files once the task is completed.

Now, let’s run a task to compile the Sass.

In terminal

In Gulpfile.js, we’ll write:

A simple task which can be used to compile Sass and create style.css!

To execute [‘sass’], simply type the following command into your terminal:

Gulp can automatically compile Sass each time we save a Sass file

In your terminal, simply type

Now, anytime you make changes and save any file with a .scss extension, it will trigger this [‘watch’] task which executes [‘sass’].

Gulp is a task runner that uses Node.js as a platform. Gulp purely uses the JavaScript code and helps to run front-end tasks and large-scale web applications. It builds system automated tasks like CSS and HTML minification, concatenating library files, and compiling the SASS files. …

Read More

Background Workers using Crontab

Scheduling background jobs is a common task in rails application development. Eventually what we want is a cron job which runs the schedule jobs.

cron is the system process which will automatically perform tasks for you according to a set schedule. The schedule is called the crontab, which is also the name of the program used to edit that schedule.

For example, let’s say you have a rake task which you want to run every hour.

To edit the crontab, use this command:

Now let’s add our job to the crontab. Each job you add should take up a single line.

The format is very simple: six pieces of information, each separated by a space; the first five pieces of information tell cron when to run the job, and the last piece of information tells cron what the job is.

m, representing the minute of the hour, h, representing the hour of the day, dom, representing the day of the month, mon, representing the month of the year, dow, representing the day of the week and  command, which is the command to be run. For example in our case

The asterisks (“*“) will tell cron that for that unit of time, the job should run ‘every’. Save and close the file.

And that’s it.

But sometimes fiddling with crontab on the server can be very hectic and it would be much better if we can configure cron job in our rails application so we can keep the configuration in our source control.

We have a gem called whenever that allows us to set up cron jobs from within our Rails apps using Ruby code. Let’s see how you can schedule our background jobs in Rails using Whenever to set up your schedule.

Add in your Gemfile.

Run bundle install to install the gem.

Run the wheneverize command in your app’s root folder to set up an initial configuration.

The wheneverize command …

Read More

Cheat sheet for managing files from Ruby

In this Cheat sheet, you will learn managing files from Ruby.

Files are used for storing the Data for a Long time Period. And the files can contain any type of information means they can Store the text, any Images or Pictures or any data in any Format. It is associated with class IO File includes.

Creating a New File

New files are created in Ruby using the new method of the File class. The new method accepts two arguments, the first being the name of the file to be created and the second being the mode in which the file is to open. Like,

file =“filename”, “mode”)


Supported modes are:

Read only access.

Read and write access.

Write only access.

Read and write access.

Write only access.

Read and write access.

Opening Existing Files

You can open the existing files using the open method.


If the file is already opened, we can close it by using the close method.


Reading and Writing Files

Once we’ve opened an existing file or created a new file we need to be able to read from and write to that file. We can read/write using different methods.

sysread Method:

You can use the method sysread to read the contents of a file.


This statement will output the first 10 characters of the file.

syswrite Method:

You can use the method syswrite to write the contents into a file.


It writes ‘Hello’ into the file input.txt.

each_byte Method:

This method belongs to the class File. The method each_byte is always associated with a block.


Characters are passed one by one to the variable ch and then displayed on the screen.

IO.readlines Method:

The class File is a subclass of the class IO. This method returns the contents of the file line by line.


Each line of the file input.txt will be an element in the array arr. Therefore, arr[0] will contain the first line, whereas arr[1] will contain the second line of …

Read More

Get into Sentiment Analysis with Ruby


Sometimes we fail to understand other’s emotion. So how it will be when machines try to understand ours? When writing programs we care about the syntax and structures but these concerns are not there in communication between people. To process our language machines have to understand not only what we say, but what we mean. Natural language processing is a fascinating subject to explore. But what makes it complicated?

Human communication isn’t just a group of words. It’s a mix of sentiments which needed to be analyzed to understand what we really mean.

Why should I care

The contemporary business world is a place where huge success and failure sit side by side. In traditional market research, business spends a huge amount to analyze customer’s opinions through continuous surveys and consultants. But nowadays social media empowers business a lot. Most the existing and potential customers are generating a treasure trove of data through Twitter, Facebook, LinkedIn and so on. Sentiment analysis is a powerful tool for mining the gold beneath the social media landslide.

The goal of sentiment analysis is to identify the opinions expressed in a text.

It seems easy, right?

  • I’m happy to watch a new movie
  • I hate war
  • Since happy is a positive word and hate is negative, we know the sentiments in each sentence. This is the most simple situation.

    But what if a text contains two opinion words and one sentiment?

    If we assign +1 to positive word and -1 to negative word,

    • I’m happy and excited to be going to watch a new movie

    The above sentence is positive +2

    • I hate war and the violence it makes

    The text contains two negative words so it is negative -2

    Now, let’s consider a text with mixed polarity.

    That’s, two opinion words and two sentiments

    What we learned is adding +1 and -1 equals 0 but here it doesn’t mean that the text …

    Read More

    Refactoring in Rails


    When the complexity of our Rails application increases, it becomes difficult to test and add new features. As we know, Rails is built on the principle of convention over configuration. Putting too much logic in the controller will eventually violate the single responsibility principle making future changes to the codebase difficult and error-prone. Refactoring the code helps for quality, clarity, and maintainability.

    When should we refactor?

    Tests usually run faster with well-isolated code. Slow running tests indicate the need of more sophisticated design. For example, each class should be concerned about one unique functionality. Also, models and controllers with too many lines of code needed to be refactored to make code DRY and clean. We can use best approaches of Object Oriented Programming to achieve this.

    Consider the following example of a controller where the whole logic for creation and deletion is concentrated.


    Moving a big controller’s action to service objects

    To achieve the new design, keep controllers as thin as possible and always call service objects. Controllers are a good place to have the HTTP routing, parameters parsing, authentication, calling the right service, exception catching, response formatting, and returning the right HTTP status code. A service object’s job is to hold the code for a particular bit of business logic.

    Calling services from controllers result in many classes each of which serves a single purpose. This helps to achieve more isolation between objects. Another important thing is that service objects should be well named to show what an application does. Extracting code from controllers/models to service objects would support single responsibility principle, which leads to better design and better unit tests.

    The above example can be rewritten by calling separate services for creating and deleting as shown below. This considerably reduces the number of lines of code in the controller and provides more clarity on …

    Read More

    Getting started with Angular 4

    Angular is a most popular platform for building applications with the web. Angular empowers developers to build applications that live on the web, mobile, or the desktop. The AngularCLI is a command line interface tool that can create a project, add files, and perform a variety of ongoing development tasks such as testing, bundling, and deployment.

    As compared to the older versions of Angular, there are many new things added to the list. Not only new features but also some twists are there that enhance old features. Forget Angular 3, Google jumps straight to Angular 4 after Angular 2. Angular4 applications are much faster and less space consuming.  Angular4 is compatible with TypeScript’s newer versions 2.1 and 2.2. Components are the basic building blocks of your application. Every component has an associated template, style sheet, and a class with logic.


    1. NodeJS ( 6.x.x or greater )

    2. npm (3.x.x or greater )


    1. You have to install AngularCLI globally.

    2. Create a new project.

    3. To serve the application, get into the project repo and run :

    For launching our server and for rebuilding our app when there are any changes we are using “ng serve”.

    When using “–open” or “–o”, it will open in “http://localhost:4200/” automatically.

    And that’s it!

    Your basic app is ready!

    What’s New In Angular 4

    Router ParamMap

    In the previous versions, we were using a simple key-value object for storing route parameters. But in Angular4, it is possible to query a so-called ParamMap in the router, that is a request for the route- and query parameter assigned to a route.

    Now, we can run them as simple method calls (parameterMap.get(‘parameter-name’)).

    The parameters are also available as a map. This brings advantage in terms of type security. The old key-value structure is unsafe since it can take …

    Read More