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.

Authentication

Basic and Token authentication are handled by Faraday::Request::BasicAuthentication and Faraday::Request::TokenAuthentication respectively. …

Read More

Cheat sheet for managing files from Ruby


Bookmark and Share

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 = File.new(“filename”, “mode”)

Eg:

Supported modes are:

r
Read only access.

r+
Read and write access.

w
Write only access.

w+
Read and write access.

a
Write only access.

a+
Read and write access.

Opening Existing Files

You can open the existing files using the open method.

Eg:

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

Eg:

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.

Eg:

This statement …

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

Rails Generators


Bookmark and Share

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

Read More

How we made our rspec test suite to run 2x faster


Bookmark and Share

 

Why on earth is my test suite taking so long to run?

If you are a developer, you might have asked this question at least once to yourself. So did we, our rails project’s test suite was taking a good 1 hour 30 minutes to run and we wanted to improve that time so badly that we eventually did exactly that, reducing nearly 1 and half hours to just minutes, and this is how we did it.

1. Database independent tests

DB operations are often time-consuming and most of the time we can do away with saving objects to the database to run our tests.

Use test doubles, stubs and mocks instead of creating the real instance of a class and invoking methods on the created instance.

Our test case

This test can be made faster by replacing

with

2) Use gem group

Rails preload your gems before running tests. Using gem groups allow rails to load only the environment specific dependencies.

#Gemfile

3) Use before(:each) and before(:all) hooks carefully

Since before(:each) runs for every test, be careful what we include inside before(:each) hook. If the code inside before(:each) is slow every single test in your file is going to be slow.

A workaround would be …

Read More

Concurrent-Ruby


Bookmark and Share

Concurrent Ruby

Concurrent-ruby is a gem that was brought my attention during Anil Wadghule’s talk in RubyConf India 2017.

Concurrency is the ability of a program to make progress on a task that is spread out over different slices of time. It allows us to run multiple “threads” at the same time. As one thread may be sleeping or waiting on I/O, another thread may take priority and start working, thus making optimal use of available CPU time. When you think of concurrency, think of “threads”.

Modern concurrency tools include agents, futures, promises, thread pools actors, supervisors etc.Concurrent Ruby makes the strongest thread safety guarantees of any Ruby concurrency library. Every abstraction in this library is thread safe. Similarly, all are deadlock free and many are fully lock free.

Concurrency Abstractions

  • Async (Concurrent::Async): A mixin module that provides simple asynchronous behavior to a class, turning it into a simple actor.
  • Future (Concurrent::Future): An asynchronous operation that produces a value. It represents a promise to complete an action at some time in the future.
    • Dataflow: Built on Futures, Dataflow allows you to create a …
Read More

Custom Loggers


Bookmark and Share

Custom loggers are useful if you wish to have a separate log file for different moving parts of your Rails application. This would make your logging more efficient and readable. (Eg: a file to record all the API request you received). Let’s have a look on them!

Note: This could cause an issue of log files growing and consuming the entire space in the hard disk can be managed by configuring Rails application. It is described in our previous article Enable log rotation within the rails application.

Rails make use of ActiveSupport::Logger class to write log information. It is used to output message and has associated levels. You can then give the Logger a level, and only messages at that level or higher will be printed. They are:

UNKNOWN
An unknown message that should always be logged.

FATAL
An un-handleable error that results in a program crash.

ERROR
A handleable error condition.

WARN
A warning.

INFO
Generic (useful) information about system operation.

DEBUG
Low-level information for developers.

CREATE YOUR CUSTOM LOGGER

It creates a custom_logger.rb file. Here defines the format for log messages. The arguments are:

  • Severity of the log message
  • Time instance representing when the message was logged
  • progname configured or passed to the logger method
  • Object the user passed to the …
Read More

Make unit tests great again – Integrate Jasmine into Rails


Bookmark and Share

Jasmine is a framework to write tests for the Javascript code in the Behaviour Driven Development (BDD) style. In this article, you will learn how to integrate Jasmine into your existing rails application and how to write clean and beautiful unit tests. Let us make tests great again!

 

Install Jasmine

To make Jasmine available to your Rails app, you just have to place the jasmine-gem (link) in your Gemfile. That will do the magic. Just make sure you have it under Development and Test group in the Gemfile as follows:

Then run this to install the gem:

After all the gems are installed, run this code to generate necessary files for Jasmine to run:

This will create the jasmine helper file and the yml file where you configure how it should run the tests.

Run tests

You can use Jasmine right after it’s installed. It can be run in several ways, the most important ones being,

  • In your browser
  • Continuous Integration Mode (CI)
  • The CI mode is usually used when you have to integrate it into your build system.

    Browser Mode

    You have to start the Jasmine server to run it in a browser. This server runs all the tests and serves the results to a webpage. …

    Read More

    to_json vs as_json in Rails API


    Bookmark and Share

    Recently we have been working on Rails API. During that time, we were curious about the difference between as_json and to_json. In this article, we are sharing the difference we learned.

    to_json in Rails API

    Let’s discuss how we started out building our APIs using ‘to_json’. to_json will return JSON string representing the hash. Option are passed to each element.

    In to_json without any option,  the returned JSON string will include all the model attributes

    to_json had some great options of ActiveRecord objects. We could just tell the method to only render certain attributes, or to include association or method calls. We had:

    • only – Only show column names in the output as specified in the list
    • except – Show all column names except the ones specified in the list

    to_json works fine and seamlessly ok, as long as the database schema is deeply coupled with the API output.When it takes the next level where we want to render a certain attribute in json it start to break.

    This will start to generate a bit load to controllers. Such methods of generating json don’t feel quite right and begin to break down. This is because the to_json is interested in ‘serializing’ a …

    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