Getting started with Faraday gem

Bookmark and Share


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. …

Read More

Get into Sentiment Analysis with Ruby

Bookmark and Share


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 …

    Read More

    Refactoring in Rails

    Bookmark and Share


    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 …

    Read More

    Web Frameworks in Crystal

    Bookmark and Share


    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 …

    Read More

    Integrating Elm with Rails

    Bookmark and Share


    Front-end languages and frameworks are changing significantly over years. The trend is towards light-weight, modular architecture. Functional programming has influenced JavaScript and its frameworks a lot. For beautiful single page web applications, Elm is a framework that can be chosen. It gets compiled to efficient JavaScript code. But when to use Elm instead of JavaScript?  If you are building complicated single page applications Elm can do better.

    Elm is a functional programming language created by Evan Czaplicki in 2012 for building reliable Web Applications. Elm is simple to use and offers much quality. Its architecture is a simple pattern for building web apps, that help you to add features quickly. Also, we can use Elm in existing projects as it can be used along with already written JavaScript code.

    Why Elm?

    Switching to functional programming languages makes it a better environment for multi-threaded applications. For example, immutability is a powerful functional concept that JavaScript lacks. But in Elm, once created value cannot be changed, thus making a thread-safe environment. Each thread need not worry about other threads when they act on data since these data are represented by immutable objects in Elm.

    While in other languages it’s hard …

    Read More

    Managing threads with Queue and SizedQueue

    Bookmark and Share

    Threads in Ruby

    To make our applications do multiple things faster at the same time, we can use Ruby threads. For a long-running application, re-using a pool of such threads can provide great performance benefits. Thread pool is a way to have a fixed set of threads doing the work, instead of creating new ones each time.

    Considering a simple program as below, we realize the importance of threads.

    You will get the sum of each array as output but the sleep(4) instruction will pause execution for 4 seconds and then continue. Thus, group1 will get the sum after 4 seconds, group2 after 8 seconds and so on, which is not feasible. In such cases, it is more economical to have threads, since we can have the sum of each array calculated independently.

    Threads allow us to execute different parts of our program independently. For implementing threads, after initializing each array,

    The add_element method definition is same but we wrapped method call in a block.

    Now, instead of getting the sum of each array after 4 seconds, 8 seconds and 12 seconds respectively, you will get the sum of all arrays after 4 seconds. This indicates better performance and efficiency …

    Read More

    Authorization with Pundit gem

    Bookmark and Share


    Security is an important aspect of application development. Two main components of security are Authentication (Who are you?) and Authorization (are you supposed to be here?). Authentication verifies the user’s identity while authorization verifies whether that user has access rights on certain resources to perform actions on them.

    Two popular gems for authorization in the rails world are CanCanCan and Pundit, we at Red Panthers prefers pundit over CanCanCan we get to write Pure Ruby Objects and keep the logic for each part separate.

    The gem CanCanCan isolates (encourages) all authorization logic into a single class. It is a drawback when the complexity of application increases. Pundit gem provides object oriented design patterns to build our own authorization system that meets project’s requirements. It enables us to keep the models and controllers free from authorization code and allows to keep the resource logic separately. This flexibility and simplicity of Pundit gem help to use it with ease.

    To start with Pundit

    Add Pundit gem to your gem file and run bundle install.

    Integrate Pundit to Rails application by adding the following line to ApplicationController.

    If you run the Pundit’s generator as below, it will generate app/policies folder which contains …

    Read More

    Taking screenshots of webpages using Ruby

    Bookmark and Share


    Recently we have been working on taking screenshots for web page while generating reports based on that website. During this endeavor, we came across some tools to achieve that. We are sharing the information we gathered here.

    The tools that we will discuss for screencapture, in  Ruby,  are:

    • PhantomJS
    • Screencap gem
    • Webshot gem

    Screencap and webshot are gems in Ruby that depends on a tool called PhantomJS. It is basically a web browser without a user interface, primarily used for testing websites. Such type of browsers are generally referred to as headless browsers,

    Screenshots with PhantomJS

    PhantomJS is quite easy to install and is multiplatform, available on major operating systems.

    To start, our script must require a reference to the webpage module then use it to create an instance:

    Use the method and pass it the arguments, the url of the webpage that we want to capture screenshot.

    instance.render() method captures the screenshot and saves it to the file specified in the argument.
    Run the script as,

    Screenshot is saved in the  directory where we run the script.

    Now what we have above is all JavaScript, but to use the phantom JS in our rails application we have gems that provide us with an easy interface to acheive the …

    Read More