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

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.

Date

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.

Eg:

Time

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

Eg:

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.

Eg:

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.

Eg:

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

Rack::Attack – secure you rails app for the real world


Bookmark and Share

Are you worried about the security issues in your Rails app? The rack-attack gem, can help you. Rack::Attack is a rack middleware which provides security to our rails application. It allows us to safelist, blacklist, throttle and to track requests.

  • If the request matches any safelist, it is allowed.
  • If the request matches any blocklist, it is blocked.
  • If the request matches any throttle, a counter is incremented in the Rack::Attack.cache. If any throttle’s limit is exceeded, the request is blocked.
  • Otherwise, all tracks are checked, and the request is allowed.

Implementation

Install the rack-attack gem, or add it to you Gemfile as:

Then tell your app to use the Rack::Attack middleware. For Rails 3+ apps:

Or you can use it in Rackup file as

By default, Rack Attack uses Rails cache. You can override that by setting the Rack::Attack.cache.store value. It is used for throttling. If you want to create use a custom adapter, for example, memory store,  create a file called rack_attack.rb in config/initializers to configure Rack Attack and put the following code in the file:

Throttle

Here we are limiting the request per seconds from the same IP address. Here we are limiting only 3 requests in 10 sec.

Safelist

Above example always …

Read More

Spice up your boring IRB (Irbtools)


Bookmark and Share

IRB stands for interactive ruby, it is a tool for interactively executing ruby expressions read from a standard input. To invoke it, type irb at the shell or command prompt, and begin entering Ruby statements and expressions. But it has some limitations. A solution to this is called ‘irbtools‘, which make using irb easier and more fun. It improves Ruby’s irb console like colored output and lots of helpful methods.

Setup

Install the gem by using:

or

Add it to your project’s Gemfile:

Usage

IRB executes code in ~/.irbrc on start-up.To use irbtools, put the following code in ~/.irbrc file:

We can start IRB directly from the code by calling,

When installing irbtools, some gems will not be installed. For example, the bond gem for better auto-completion. These are packaged as irbtools-more (requires ruby version >= 2.4). To use irbtools-more, change the .irbrc to:

and edit Gemfile as

For example, the output looks like:

Irbtools

Features

  • Colorized and output as comment by wirb and fancy_irb
  • Nice IRB prompt and IRB’s auto indention
  • Includes stdlib’s FileUtils: ls, cd, pwd, ln_s, rm, mkdir, touch, cat
  • Many debugging helpers:
    • ap – awesome_print
    • q –like p, but on …
  • 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
    Behind the scenes of hash table performance in ruby 2.4

    Behind the scenes of hash table performance in ruby 2.4


    Bookmark and Share

    Ruby 2.4 got released this Christmas with a lot of exciting features. One of the most underrated features in ruby 2.4 is hash table improvements. Before going into details about implementation, let’s first check the benchmark to know how this change gonna affect your ruby application.

    Some benchmarks are:

    Getting keys and values of a hash

    Output

    Ruby 2.3.3

     

    ruby 2.4.0

    Yeah, the above two operations executed ~ 3 times faster on my laptop. Though these numbers can vary with your machine and processor, the performance improvements will be significant on all modern processors. Not all operations became 3 times faster , average perfomence improvement is more than 50%

    If you are a ruby developer and excited to know what are the new features in ruby 2.4, then this feature gonna make your application faster and you don’t have to change anything in the code for that. Because these changes are backward compatible. If you are curious to know what happened behind the scenes of this performance boost, then continue reading.

    Hash Table

    In computing, hash table (hash map) is a data structure that is used to implement an associative array, a structure that can map keys to values. Hash table …

    Read More

    Chartkick: data visualization made easy with Ruby


    Bookmark and Share

    Recently, I’ve been using Highcharts, Google charts and Chart Js for visualizing dynamic data in my projects. But it was difficult to integrate it with the rails application. However, for every problem in Ruby, there is a gem out there to save your day and Chartkick, a Ruby gem exclusively available for data visualization is truly a savior. Chartkick can work with Highcharts, Chart.js and Google charts to create dynamic and interactive charts that draw data from the Rails application. And the best part, you just need to write one single line of Ruby code. Isn’t that amazing and powerful!

    Let’s begin with Installation

    For installation, all you have to do is adding this line to your application’s Gemfile:

    Then you have to choose your charting library.
    In case, if more than one charting library is loaded, choose between them with the following code:

    P.S:- highcharts is the default adapter is nothing else is defined.

    Using Chartkick

    Once it’s installed, you can start playing around with chartkick. For example:

    In the above example, I have just shown you how we can make a line chart.Similarly, you can create Pie chart, Column chart, Bar chart, Area chart, Scatter chart, Geo charts, Timeline(Google …

    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:

    Eg:

    Generating the mailer

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

    Read More

    Lambda vs Proc Vs Blocks


    Bookmark and Share

    The difference between these three is one of the most baffling concepts to grasp while anyone starts to learn ruby. Since at Red Panthers we recruit and build our own team from freshers, we too will be blogging about it here to make it easy for the beginners.

    But before we state the difference between the three, let me explain what all these three does to make it easy for you.

    Blocks: They are called closures in other languages, it is a way of grouping code/statements. In ruby single line blocks are written in {} and multi-line blocks are represented using do..end

    An interesting fact about ruby is that all methods in ruby accept a block, even if you don’t declare a variable to accept it. So for example, take the method below

    It can accept a block as below

    The code is valid, but the output will have only puts “Hello World”.

    Why? because we passed in the block but it is not getting called. To run the block passed within your method you need to use the yield command.

    Now it will print

    But since we placed yield, it would now be expecting a block to be always passed in. So we need to …

    Read More