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.

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 is necessarily neutral.

    • Ice cream shops are doing great even when the weather is bad

    The statement is positive about ice cream shops but negative about weather condition. In general, we will say that this is a positive statement about ice cream shops. We wouldn’t say this is neutral.

    When SA turns hard

    Sometimes it’s not possible to identify the opinion by just analyzing the polarity of words. Language usage and sarcasm are some of the reasons why sentiment analysis turns hard. It’s …

    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

    Rails Generators

    Rails generators are used to create many files for models, controllers, views, unit tests, migrations and more. It will do some of the manual work for us. So it saves time. They can also be used to set up some basic specs for the application test suite.

    Running rails generate(or rails g) by itself gives a list of available generators:

    The main generators that rails offers are:

    • controller: The Rails controller coordinates the interaction between the user, the views, and the model.
    • helper: Code in helpers is included in the corresponding view. We can move big loops, method calls or other logic into a method in the helper.
    • mailer: It allows for sending and receiving emails from and to your application.
    • migration: Rails Migration allows you to use Ruby to define changes to your database schema.
    • model: It is Ruby class that talk to the database, store and validate data, perform the business logic.
    • scaffold: It refers to the auto-generation of a simple set of a model, views and controller usually for a single table.

    Following is the list of options, which can be used along with generators:

    -h, [–help] # Print generator’s options and usage
    -p, [–pretend] # Run but do not make any changes
    -f, [–force] # Overwrite files that already exist
    -s, [–skip] # Skip files that already exist
    -q, [–quiet] # Suppress status output


    You can create different generators by running rails g in the terminal. Let’s have a look at each of them.

    • rails generate model ModellName

    It generates the model and the associated database table. For example, we can add a new model to the app called User with fields name and age as,

    Eg:  rails g model User name: string age: integer

    • rails generate controller ListController show edit

    It generates controller. It is used if you are creating static views or non-CRUD related features. Let’s create a user controller that will …

    Read More

    PostgreSQL 9.6 new features

    POSTGRESQL is an open-source object-relational database system. It is not controlled by any corporation or other private entity. The source code is available free of charge. PostgreSQL supports transactions, subselects, triggers, views, foreign key referential integrity, and sophisticated locking.

    New features in Postgres are:

    • Parallel execution of sequential scans, joins and aggregates.
    • Avoid scanning pages unnecessarily during vacuum freeze operations.
    • Synchronous replication now allows multiple standby servers for increased reliability.
    • Full-text search can now search for phrases (multiple adjacent words).
    • postgres_fdw now supports remote joins, sorts, UPDATEs, and DELETEs.
    • Substantial performance improvements, especially in the area of scalability on multi-CPU-socket servers.

    Parallel execution of sequential scans, joins and aggregates

    PostgreSQL can devise query plans which can leverage multiple CPUs in order to answer queries faster. This feature is known as the parallel query. Mostly, queries that touch a large amount of data but return only a few rows to the user will get benefit by using Parallel Query. It can now execute a full table scan in multiple parallel processes, up to the limits set by the user.

    Avoid scanning pages unnecessarily during vacuum freeze operations

    Freezing of table is sometime necessary to guarantee safe transaction id wraparound. Previously it scanned all heap pages but now it will scan the pages modified only from the last seen. It is very helpful in cases of rarely written tables.

    Synchronous replication now allows multiple standby servers for increased reliability

    Two new options have been added to PostgreSQL’s synchronous replication feature allows it to be used to maintain consistent reads across database clusters. First, it now allows configuring groups of synchronous replicas. Second, The “remote-apply” mode creates a more consistent view of data across multiple nodes. These features support using built-in replication to maintain a set of “identical” nodes for …

    Read More

    Web Frameworks in Crystal


    The creator of Ruby, Yukihiro Matsumoto said that the language was made to make programmers happy. Imagine a language as elegant as Ruby and blazingly fast as C. If you already love Ruby, maybe it is time to start considering Crystal lang, the younger sibling of Ruby. It is a compiled language which is syntactically very similar to Ruby and designed for high throughput and performance.


    • Native WebSocket support
    • Compiles to efficient native code
    • Statically typed => if any errors it will let you know at compile time.
    • Less memory consumption

    Web frameworks in Crystal

    Applications developed using framework are easy to maintain and upgrade at a lower cost. This article lets you get familiar with some of the most popular frameworks of Crystal.

    Install Crystal to get started.

    Create our Crystal app


    To know the true potential of Crystal, let’s familiarise with Kemal, most popular Crystal framework. It’s a Sinatra inspired framework.

    Install Kemal

    In our app,

    Open in an editor and add Kemal as a dependency in the shard.yml file.

    To get dependencies, run

    This will install Kemal.

    This is similar to adding gems in gem file and bundle install in Rails.

    In the file created in the src directory, substitute the following

    In the terminal run

    We can see logs in the terminal as Kemal is ready in localhost.

    Using WebSockets is quite easy with Kemal. (Will be explaining it in our another blog)


    Like Sinatra inspired framework Kemal for crystal, Amethyst is Rails-inspired framework for crystal which is extremely fast and flexible in application development.

    Installation is similar as Kemal; add as a dependency in the shard.yml file. To start using Amethyst, require it in project code.

    For fastest and lightweight framework in crystal we could choose Kemal or if interested in something more like Rails rather than speed Amethyst can be a better option. For controllers and to describe routes, Amethyst has a Rails-like …

    Read More

    Event Listeners in VueJS

    Vue.js is a Javascript framework for user interface. There are many directives in Vuejs. A directive’s job is to reactively apply special behavior to the DOM when the value of its expression changes. You can use the v-on directive to bind event listeners to DOM events.

    We are binding a click event listener to a method named clickMe. Here’s how to define that method in our Vue instance. Here we have a counter variable initialized to zero. Inside the method, we are incrementing the value of the counter. So for each click on the button, the method is invoked. You will get the code here.

    Here in this example, we are using two button and methods. One for incrementing the count and other for decrementing. You can see code here.

    Note :-

    For example,

    This will give same result as before.

    We can see another example. Here we have an input field where we type the url which is bound to the Js using v-model.  We have a button with click event listener which is bound to the method humanizeUrl. We have two urls, url and cleanUrl. url  is what we type in the input field and cleanUrl  is getting by replacing the url using regular expression. Regular expression is not a Vue.js thing. Its a universal programming format. We are saving the domain name of url in the cleanUrl. Thus we will get the value on cleanUrl in the view. You will get the code here.

    But here you won’t redirect to the url when we click on it. That is we have to get the url. So we need to bind the href. You can use v-bind directive for this.

    Here is the Demo. So the url will redirect to the correct page. You can try out these …

    Read More

    Using mina to deploy a particular commit

    Mina is our tool of choice when it comes to automating our deployment. It might not be the best tool out there, but it is enough to get us started. Single server or multi server, we love Mina.

    In most of uses cases if something fail in production we just need to rollback to one or two version before to it. But recently we had a case in which we had to revert to version order than the previous 5 version (5 is default no of versions stored). The quick thing that we did at that point is copy of master called temp-master branch and changed master to the version that we wanted and had the new master deployed.

    We didn’t like that solution much, so we decided to look for a cleaner solution. Looking at the source code of the git task inside mina, we found that mina had an option to deploy a particular git commit. The config was set :commit, HASH (Thee cheers to the contributors to mina for having that).

    Now that made our life easier for the future. We just added the following line to our deploy.rb

    set :commit, ENV[‘COMMIT’]

    so now we can deploy a particular hash by passing that hash as an environment variable.

    mina deploy COMMIT=thegitcommithash

    note: If no hash is passed (eg: mina deploy), it would just deploy the master.


    Read More

    Two way binding in Vue.js

    Vue.js is a JavaScript framework getting popular considering its simplicity praised a lot these days. There are a lot of JavaScript frameworks among which React and Angular are popular among web developers. Vue.js is much flexible and less opinionated framework than Angular. It’s similar to React but much simpler. Vue.js supports Two-way binding. That is it keeps your data in sync with your DOM without you having to do anything. Two-way binding in Vue.js is MVVM pattern. That is Model View View Model. Like MVC, Model is the data object and view is what is displayed up. The Model can tie to the View and the View can tie back to Model.

    In one way binding, JS variable is bound to the DOM.

    Here when you change the data in JS, it will also update in the DOM. So you will get the updated message on the page. You can get the basic code here.

    But in two way binding, Js variable can be bound to the DOM and data is also bound from the DOM back to JS.

    Now, if you type anything into your input, your JS variable is updated with the change, which in turn updates your span. You can get the code here.


    The attribute used with input v-modelis a vue directive. We have to assign data model with the directive. A directive’s job is to reactively apply special behavior to the DOM when the value of its expression changes. In the case of v-model, it binds the element to one of the data properties that Vue is watching. Vue has many directives. Another one is v-on which binds an element to an event. For example, v-on: click  is to bind element when clicking on it.

    Working with html forms is a breeze in Vue. This is where two-way binding shines. It does not bring any issues  even in complex …

    Read More