Observer Design Pattern in Ruby


Bookmark and Share

Observer design pattern (also known as Publish/Subscribe) is a software design pattern, used when we are building a system where the state of one object affects the state of other objects. It is a key part of model-view-controller architectural pattern.

In a traditional MVC ( Model-View-Controller ) architecture, a model is a subject and a view is an observer. A view is notified when a model changes and responds accordingly. When the subject sends observers detailed information about what has changed, indiscriminately, this is known as the push model of the Observer pattern. When a subject sends only minimal information to its observers must ask for details explicitly, this is known as the pull model of the Observer pattern.

Observer Design Pattern

Ruby provides a simple mechanism to implement this design pattern using the Observable module. In this mechanism, the Notifier class uses the Observable module, which provides the methods for managing the associated observer objects.

The observable object must:

  • assert that it has #changed
  • call #notify_observers

An observer subscribes to updates using #add_observer, which also specifies the method called via notify observers. The default method for notify observers

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

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

    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

    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