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

    Readability of text using odyssey


    Bookmark and Share

    When you are writing something like article, text, document etc you are focusing on readability. If you are not then you should. As readability influence how a reader can read and understand the content, how you are presenting the content etc. It would also influence how much likely one is to share your article as well. To find the readability there are a lot of statistical tests. Few are listed below.

    • Flesch-Kincaid readability test
    • Flesch Kincaid Grade Level

    • Gunning Fog Score

    • SMOG

    • Coleman Liau Index

    • Automated Readability Index (ARI)

    Recently in a project that we worked on we were asked to find the readability of various pages of a website. We decided to start with Flesch-Kincaid test, as we found this to be a popular one in our research.

    Flesch-Kincaid readability test is designed to indicate how difficult a passage in English is to understand. In this test higher score indicates how easier to read and a lower score indicates how difficult it is to read.The formula to find Flesch-Kincaid reading-ease score is

    206.835 – 1.015 * (total words / total sentences) – 84.6 * (total syllables / total words)

    The scores can be interrupted as

    Score
    School Level
    Notes

    100.00-90.00
    5th grade
    Very …

    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

    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