Friday, 1 December 2017

Ruby on Rails Is Scalable?

Ruby on Rails is a great framework for startups, but we often hear people talk about Rails scalability issues when a startup project grows too large (read: becomes very popular).

One of the key events that triggered the discussion that Rails can't scale was when Twitter switched to Scala in order to handle their growing number of user requests.

But as a counterexample, we would like to mention that Shopify is an advanced Rails application that has scaled quite well many years in a row. So who’s right? Do you need to ditch this framework if your app goes big?

Let's take a look at how to scale a Ruby on Rails application to find out.

What Is Rails Scalability?

A framework’s scalability is the potential for an application built with this framework to be able to grow and manage more user requests per minute (RPM) in the future. Actually, it's incorrect to talk about framework scalability, because it's not the framework that must, or can, scale, but rather the architecture of the entire server system. But we should acknowledge that, to a certain extent, application architecture does have an impact on scalability.

In short, telling 'How to scale Ruby on Rails' or 'Ruby on Rails scalability issues' is basically incorrect.

Let's take a look at the example below. This is what the entire server architecture looks like at the very beginning of a Rails project.



what we usually have is a single server, on which we install the following software:

  •     Nginx server;
  •     Rack application server – Puma, Passenger, or Unicorn;
  •     Single instance of your Ruby on Rails application;
  •     Single instance of your database; usually, a relational database like PostgreSQL.

This server computer will be able to cope with, say, 1,000 or even up to 10,000 requests per hour easily. But let’s assume that your marketing is very successful, and your Rails application becomes much more popular; your server starts getting 10 or 100 times more requests. When the load increases to a high enough level, a single server architecture cracks under pressure. That is, the application becomes unresponsive to users.

That’s why we’ll explain how to resolve this scalability issue – serving data to users – with Ruby on Rails.

Let's Scale Your Ruby on Rails Application!

Vertical Scalability with Ruby on Rails

Scaling vertically is the simplest way to make the server handle an increased number of RPMs. Vertical scaling means adding more RAM, upgrading the server’s processor, etc. In other words, you give your server computer more power. Unfortunately, this approach doesn’t work in many situations, and here are a couple of reasons why.

Vertically scaling a server running an app gives a positive effect only at the initial stage. When your traffic increases yet again, you eventually come to the point when upgrading the processor or adding more RAM is technically impossible.

But there’s another downside to this approach. When you need to scale your Ruby on Rails application, there are usually some parts that demand more computational resources than others. For example, Facebook needs servers offering different performance for updating the news feed and processing images. Image processing is used less frequently than the news feed. Therefore, Facebook installs a less powerful server for image processing than for the news feed. We’ll talk more about this architectural approach (Service-Oriented Architecture or SOA) to scaling Rails app shortly.

When vertical scalability is no longer practical, or when we look for other scalability options right away, we scale a Rails application horizontally.


Horizontal Scalability with Ruby on Rails

We can scale a Rails application horizontally similarly to how we scale with many other frameworks. Horizontal scaling means converting the single server architecture of your app to a three-tier architecture, where the server and load balancer (Nginx), app instances, and database instances are located on different servers. In such a way, we allocate equal and smaller loads among machines.


Nginx


Nginx, a commonly used server software for Rails applications, is deployed on a single machine to serve as a load balancer and reverse-proxy. You need a medium-powered server for Nginx, because this server requires little computing power to function normally under high loads. Nginx’s sole aim is to filter and distribute the load among multiple servers.

We set up this server to receive the initial request and forward it to the first machine. The second request will be sent from Nginx to the second machine, and so on. When you have only three machines with your Rails application instances, then the fourth request from the client (browser) will be sent, naturally, to the first machine again.

App Instances

As we mentioned previously, you need additional servers to run app instances separately from the Nginx server. From the user’s perspective, the app stays the same; they simply access different app instances thanks to Nginx.

For communication between the application and Nginx, we use a special interface called Rack, which is an application server. There are many application servers for Rails-based apps, the best known being Unicorn, Phusion Passenger, and Puma. Application servers are responsible for input-output, letting the application deal with user requests.

Although Rails applications are mostly monolithic, we can extract a functional block and use it as a standalone service. This will also lessen the load on servers.

Database Instances


Scaling a database is another important aspect of scaling a Rails application. We can deploy a database on the same server as the application to economize, but this economization has several drawbacks. When every application instance saves and retrieves data from its own database instance, then data for the entire application is spread across many machines. This is very inconvenient for website users. If Nginx redirects a user to a different app instance than where their data is stored, they can’t even sign in because their data is located on a different machine!

Another reason to separate a database from other servers is to create a fault-tolerant architecture. If our database receives too many requests and can’t manage them, it collapses. But other database instances in the data tier can accommodate this load, and the Rails app will continue to work.

That’s why, when you are ready to scale your Rails application, your database should be transferred to its own server right away. The database tier can be a single server with a database that’s used by all app instances. Or, this tier can consist of several machines each running databases. In order to update data across all databases, we use database replication. Once a database has new data to share, it informs all others about changes (which is standard procedure for multi-master relationships among databases).

In a master-slave replication variant, databases communicate with the master (or main) database, which stores important data about other databases. All other database instances receive updates only when the master database updates data. Multi-master database replication and master-slave replication are the two common approaches to making our data layer consistent across multiple databases.

When the database receives a large quantity of data, it must save it quickly, update its status quickly, and send new data back to the user. An ordinary relational MySQL database is usually replaced by PostgreSQL or MongoDB databases to accommodate large quantities of data when you scale an app.

In order to further reduce the load on the database, several other techniques can be used. Caching is one important solution, although it’s indirectly related to database scalability. Caching provides cached data from a storehouse to a client more quickly. Imagine that your Rails app compiles statistics about user activity, such as user sessions. This produces a high load on the CPU. We can calculate this information once per day, and then show the cached data to the user at any time.

The other two solutions for reducing the load on a database are Redis and Memcached, which are special databases that perform read/write operations extremely fast.


Other Options when Scaling a Rails App

Let's say you want to spend as little money as possible on new servers. Is it possible to scale your Rails application while minimizing server costs? Indeed it is.

First, consider code optimization. Let's assume your service offers image editing, which is demanding on the the CPU. Given that your startup has evolved very quickly, it’s almost a given that your image editing algorithm wasn't optimized in its initial form, so there’s a lot of code to refactor and optimize. For example, at RubyGarage we needed to parse a huge CSV file with a user data. It took as much as 74 seconds for the algorithm to parse the file. But when our developer removed unnecessary checks and reused some resources, the algorithm took only 21 seconds to accomplish the same task. Code optimization helps you get more out of existing server resources.

Another option is to re-write computationally intensive tasks in a low-level language, such as C++. Due to low concurrency support – because of the Matz Ruby Interpreter (MRI) – Ruby isn't so great for computation compared to low-level programming languages.

It's also possible to stick with Ruby and Ruby on Rails in your project, but deploy a service-oriented architecture in order to scale your application. Imagine your project uses chat functionality (as one of our client’s apps does). The chat can be loaded with many requests from users, while the other parts of this application are used infrequently. It's unnecessary to break the server structure into three tiers. But it's possible to break the application into two parts!


We deployed the application part responsible for chat functionality on a separate server as a stand-alone application. Chat could then communicate with the original application and database, but the load on the main server was decreased. Further, it will be easier, faster, and less expensive to scale just this small part of your application – either vertically or horizontally – should the load increase once more. The service-oriented architecture is a great solution for scaling Rails application and is used by many companies, including Facebook and Shopify.

Ruby on Rails Application Architecture and Scalability

We mentioned before that the Rails application architecture can negatively affect scalability. Scalability issues become apparent if an application consists of many services that cannot run separately from other services.

Let's consider an example of a bad Rails application architecture. An application can constantly save its current status when a user enters new data in a form or visits several web pages successively. If the load balancer redirects this user to the next server, this next server won't know anything about this new data. This will prevent us from scaling the app horizontally. The application’s status must be saved either on the client (browser) or on the database.

If we avoid this common architectural mistake, or similar mistakes, when building a application, we will be able to scale it with no trouble.

Tools that help you scale Rails apps

Proper scalability of a Rails application is only possible when you find and eliminate bottlenecks. Finding bottlenecks is a bit difficult to do manually. And we can’t figure out scalability issues by just scratching our heads.

A much more effective way to locate problems when scaling applications is to use dedicated software. New Relic, Flame Graphs, Splunk, StatsD, and other software programs are all great options, and they work similarly: each checks and collects statistics about your application. We must then interpret the gathered data to figure out what to change.

We can use Flame Graphs to learn about CPU or RAM loads when running our application. When the app interacts with the database, we can track code paths. Learning what processes take the most time can lead us to our application’s bottleneck(s). When we’ve identified a bottleneck, we can design a solution to remove it.

You can see a strangely looking graphic with vibrant colors, which we took from Flame Graph, in the screenshot below. No matter it's appearance, the graphic is genuinely helpful to track how our code works from the very beginning.






In conclusion, we would like to repeat what Shopify said several years ago at a conference dedicated to Ruby on Rails scalability: “There isn't any magic formula to scaling a Rails application.”

In this article, we mentioned some problems that might appear when scaling a Ruby on Rails application, and described several solutions. But applications are unique. Therefore, you must know the characteristics of your particular application in order to overcome your applications specific limitations. It's important to know exactly what part of a Rails application to scale initially as we begin optimizing from crucial issues down to minor bottlenecks.

Monday, 6 November 2017

How to choose a technology stack for web application development

CRITERIA FOR CHOOSING A TECHNOLOGY STACK

Type of Web Application
The first thing to decide upon is the type of web application you’re developing. A tech stack is a toolset for creating a web app, so you need to fully realize what you’re planning to build in order to pick the appropriate tools. You should find a toolset that provides unique advantages for your web application.
In terms of complexity, all web projects can be divided into three types:
  • Simple. These web applications are created with the help of out-of-the-box solutions (such as CMS software, for example). Examples: landing pages and simple online stores.
  • Mid-level. These apps have more functions than simple apps and are built with the help of frameworks. Examples: apps for large e-commerce stores and enterprises.
  • Complex. These web apps have lots of functions and integrations; they’re developed with the help of different web development technologies and may be composed of several programming languages. Examples: social networks, large e-commerce marketplaces, fintech software, etc.
Knowing the type of web app you’re developing isn’t enough; you should take its business goals into account as well. This is important since your business goals impact the choice of technologies for development. Your web app can be tailored for:
  • Processing heavy loads. If your web project relies on load processing, you should opt for programming languages and frameworks that can provide this. Examples of such projects are video/audio streaming apps and file sharing services.
  • Low latency. A different tech stack is required to make your web application highly responsive and to reduce latency. Social networks are probably the best example of websites that require low latency.

Time to Market

Time to market (TTM) is extremely important when choosing a tech stack for startups and for small businesses. The faster you develop and release your application, the more ahead of competitors you’ll be. Moreover, the less time development requires, the cheaper the development cost.
TTM heavily depends on the technology stack you select for your web application, and here’s a list of issues you should consider when choosing a proper stack:
  • Out-of-the-box solutions. Check whether a technology has some out-of-the-box solutions for adding some necessary functionality to your web application. For example, the Ruby on Rails framework allows developers to use lots of open-source libraries (called gems) that facilitate the development process and significantly reduce TTM.
  • Integration with third-party solutions. Make sure the tech stack you choose supports integration with third-party solutions, as it’ll help you add the functions you need to your web application without reinventing the wheel.
  • Developer availability. Even if you’ve decided upon the tech stack, there’s still a problem: you need developers to do all the coding. You should check whether you’ll be able to find developers with expertise in the technology stack you choose. And remember that building a web application is just the beginning. You also need developers to maintain it after launch.
  • Documentation and developer community. Producing good code is difficult, and any development team may stumble over some tricky issues. It may take quite long for a team to find a solution, which means, in turn, a missed web project release deadline. That’s why you should find out whether the technologies you’re going to select have large developer communities and rich documentation.



image of number of Github contributors

  • Easy to test. A web application contains many lines of code, so bugs are inevitable. Needless to say, removing all bugs requires a lot of time and slows down development. To counter this problem, choose technologies that are easy to test. Some technologies are based on a so-called test-driven development approach, which implies that testing goes first and coding comes after. Test-driven development allows you to guarantee your code and product quality and speed up development in the medium and long term.

Development Cost

Needless to say, turning your idea into a real-life web application isn’t free of charge and requires investment. The choice of a website technology stack has a direct impact on the development cost. There are two main issues you need to take into account:
  • Developer salaries. Web developers are highly skilled professionals who are rather well-paid. Their salaries, however, depend on the technologies they work with. Consequently, your expenses will be different depending on tech stack. You should remember that the more advanced the technology is, the higher the developer salary will be.



image of average developer salaries in the US

  • App maintenance cost. Creating a web application is just one side of the coin; maintaining it is the other. To reduce maintenance costs, you should opt for free open-source technologies. For example, the Ruby on Rails web development framework is available with the MIT licence, which means it can be modified, upgraded, and used without any restrictions.

Security

Our world has gone digital over the last two decades and so have criminals. Cyber attacks are the biggest threat to online businesses: according to a forecast by Juniper Research, annual financial losses from data breaches are expected to reach a mind-blowing $2.1 trillion by 2019. Today, governments and corporations are working hard on ensuring the highest level of cyber security possible.
No doubt, you want your web application to be secure. Hence, you should pick technologies that allow you to create a really secure app. There are lots of different opinions as to which programming language is the safest, but in truth, no language guarantees 100% safety.
Every web development technology serves its purpose, so you should choose the right tool first and follow security guidelines second. Most web development technologies have security guidelines where all steps for preventing threats and minimizing vulnerabilities are given. You need to make sure that your web app is created in accordance with the appropriate security guidelines.

Scalability

Scalability isn’t a feature to turn tail on when developing a web application. No doubt you wish to see your web project grow and gain popularity. In general, there are two kinds of scalability:
  • Horizontal scalability, which means the ability of a web application to accommodate more requests. In other words, an app must be able to work if the number of users grows dramatically.
  • Vertical scalability, which means the ability to add new components to a web application without damaging its performance.
You should think of scalability in advance and choose an appropriate technology stack for your needs. This may seem a difficult choice as you’ll probably come across a number of contradictory opinions. However, we recommend relying not on someone else’s words, but on concrete examples of why exactly a certain technology is scalable.

TECHNOLOGY STACKS BEHIND SUCCESSFUL WEB PROJECTS

By now, you are almost certainly curious about some modern web application stacks. Let’s take a look at what technologies power some of the most successful web projects:



Airbnb, the world’s most well-known hospitality service that helps millions of people find rental apartments and short-term lodging, is largely based on Ruby on Rails.
image of Airbnb stack

Shopify helps entrepreneurs power their online stores. Ruby on Rails is the core technology behind this super-successful web service.
image of shopify stack

Quora is a question-and-answer website where people can find answers to each other’s questions.
image of quora stack

Instagram, a mainstream social networking application, is built with Python.
image of instagram stack

Product Hunt is a popular service that allows users to share information about products and find new products on the web.
image of product hunt stack

Codecademy is an online educational platform that offers free coding classes in 15 programming languages, including Ruby, Python, and Java.
image of codecademy stack

Pinterest is a social network aimed at helping people share and find new interests.
image of pinterest stack

Reddit is a popular news aggregator and discussion platform.
image of reddit stack

Coursera is a venture-backed educational platform that offers a variety of online courses on different subjects.
image of coursera stack

Facebook is the world’s biggest social network with almost 2 billion active monthly users.
image of facebook stack

PICK A TECHNOLOGY STACK ACCORDING TO YOUR PROJECT

As you can see, selecting the right tech stack is a real challenge, but the core idea that should guide you is as follows: choose the technologies according to your project. You shouldn’t rely on time-proven technologies only, even if they have been used by some large and successful companies or prominent projects have been accomplished with their help.
You should always be realistic and take all pros and cons into account. The wrong choice of a technology stack may end in financial losses, so if you aren’t experienced in web development, leave the choice to professionals. A team of professional web developers will be able to choose the right tools for delivering a top-notch web application with all the functionality you need.

Thursday, 13 July 2017

Ruby Exception Handling

What Are Exceptions?

Exceptions are Ruby’s way of dealing with unexpected events.

begin
1/0
rescue
puts "Got an exception, but I'm responding intelligently!"
end

# This program does not crash.
# Outputs: "Got an exception, but I'm responding intelligently!"


The exception still happens, but it doesn’t cause the program to crash because it was “rescued.” Instead of exiting, Ruby runs the code in the rescue block, which prints out a message. This is nice, but it has one big limitation. It tells us “something went wrong,” without letting us know what went wrong.

Exception Objects


All of the information about what went wrong is going to be contained in an exception object.

begin
1/0
rescue => e
puts "#{e.message}"
end

# Rescues all errors, an puts the exception object in `e`
rescue => e

# Rescues only ZeroDivisionError and puts the exception object in `e`
rescue ZeroDivisionError => e


begin
 # Any exceptions in here...
 1/0
rescue ZeroDivisionError => e
  puts "Exception Class: #{e.class.name}"
  puts"Exception Message:#{e.message}"
  put"Exception Backtrace:#{e.backtrace}"
end

# Outputs:
# Exception Class: ZeroDivisionError
# Exception Message: divided by 0
# Exception Backtrace: ...backtrace as an array...

Most exception objects will provide you with at least three pieces of data:
1. The type of exception, given by the class name.
2. An exception message
3. A backtrace

All of the information about what went wrong is going to be contained in an
exception object.


begin
 # Any exceptions in here...
 1/0
rescue ZeroDivisionError => e
  puts "Exception Class: #{e.class.name}"
  puts"Exception Message:#{e.message}"
  put"Exception Backtrace:#{e.backtrace}"
end

# Outputs:
# Exception Class: ZeroDivisionError
# Exception Message: divided by 0
# Exception Backtrace: ...backtrace as an array...


Most exception objects will provide you with at least three pieces of data:
1.The type of exception, given by the class name.
2.An exception message
3.A backtrace


Raising Your Own Exceptions

So far we’ve only talked about rescuing exceptions. You can also trigger your own exceptions. This process is called “raising” and you do it by calling the raise method.

begin
  # raises an ArgumentError with the message "you messed up!"
  raise ArgumentError.new("You messed up!")
rescue ArgumentError => e
  puts e.message
end

This being Ruby, raise can be called in several ways:

# This is my favorite because it's so explicit
  raise RuntimeError.new("You messed up!")

# ...produces the same result
  raise RuntimeError, "You messed up!"

# ...produces the same result. But you can only raise
# RuntimeErrors this way
  raise "You messed up!"

Making Custom Exceptions

Ruby’s built-in exceptions are great, but they don’t cover every possible use case.

To make a custom exception, just create a new class that inherits from StandardError.

class PermissionDeniedError < StandardError
end

raise PermissionDeniedError.new()


class PermissionDeniedError < StandardError
attr_reader :action
def initialize(message, action)
# Call the parent's constructor to set the message
super(message)
# Store the action in an instance variable
@action = action
end
end

# Then, when the user tries to delete something they don't
# have permission to delete, you might do something like this:
raise PermissionDeniedError.new("Permission Denied",:delete)

The  Class  Hierarchy


We just made a custom exception by subclassing StandardError, which itself subclasses Exception.

In fact,  if you look at  the  class hierarchy  of any  exception  in Ruby,  you’ll find it eventually  leads back to Exception.  Here, I’ll prove it to you. These are most of Ruby’s built-in  exceptions, displayed hierarchically:

Exception
   NoMemoryError
   ScriptError
       LoadError
       NotImplementedError
       SyntaxError
    SecurityError
    SignalException
        Interrupt
     StandardError
        ArgumentError
        UncaughtThrowError
        EncodingError
        CompatibilityError
        ConverterNotFoundError
        InvalidByteSequenceError
        UndefinedConversionError
        FiberError
        IOError
           EOFError
        IndexError
        KeyError
        StopIteration
        LocalJumpError
        NameError
           NoMethodError
        RangeError
           FloatDomainError
        RegexpError
        RuntimeError
        SystemCallError
        ThreadError
        TypeError
        ZeroDivisionError
SystemExit
SystemStackError
fatal – impossible to rescue

Rescuing errors of a specific class also rescues errors of its child classes.For example, when you rescue StandardError , you not only rescue exceptions with class StandardError but those of its children as well. If you look at the chart, you’ll see this includes ArgumentError,IOError, and many more.

begin
 #do something
rescue Exception => e
end

Rescuing All Exceptions (The Wrong Way)

begin
 #do something
rescue Exception => e
end

The code above will rescue every exception.Don’t do it! It’ll break your program in weird ways.

That’s because Ruby uses exceptions for things other than errors. It also uses them to handle messages from the operating system called “Signals.” If you’ve ever pressed “ctrl-c” to exit a program, you’ve used a signal. By suppressing all exceptions, you also suppress those signals.

There are also some kinds of exceptions — like syntax errors — that really should cause your program to crash. If you suppress them, you’ll never know when you make typos or other mistakes.


Rescuing All Errors (The Right Way)


Go back and look at the class hierarchy chart and you’ll see that all of the errors you’d want to rescue are children of StandardError.

That means that if you want to rescue “all errors” you should rescue StandardError.

begin
 do_something
rescue StandardError => e
 # Only your app's exceptions are swallowed. Things like SyntaxError are left alone.
end

In fact, if you don’t specify an exception class, Ruby assumes you mean StandardError

begin
  do_something
rescue => e
  # This is the same as rescuing StandardError
end


Advanced Rescue & Raise

Full Rescue Syntax

you have a situation that requires a more sophisticated approach to rescue an exception. Below is an example of Ruby’s full rescue syntax.

begin
 do_someting
rescue TooHotError => too_hot
 # This code is run if a TooHotError occurs
rescue TooColdError => too_cold
 # This code is run if a TooColdError occurs
else
 # This code is run if no exception occurred at all
ensure
 # This code is always run, regardless of whether an exception occurred
end

• else - is executed when no exceptions occur at all.
• ensure - is always executed, even if exceptions did occur. This is really
   useful for actions like closing files when something goes wrong.
• rescue - you know what rescue, is, but I just wanted to point out that
   we’re usingmultiple rescues to provide different behavior for different
   exceptions.

 begin
request_web_page
 rescue TimeoutError
  retry_request
 rescue
send_alert
 else
record_success
 ensure
close_network_connection
 else
 
Here, we respond to timeout exceptions by retrying. All other exceptions trig-
ger alerts. If no error occurred, we save the success in the database. Finally,
regardless of what else occurred, we always close the network connection.









Tuesday, 9 August 2016

Active Jobs

Active job is a rails framework for running background jobs, It's included as rails component as same like other components like active record, Active model etc

What is Background Jobs and why do we need?
You’re always striving to give your users a better experience when they use your website or application, 

One of the most important ways to achieve this is by giving them quick server response times and processing the non web responses in the background like Email, Payments, sms, Data processing, Video, audio upload etc..


  • Active Job was first included in Rails 4.2
  • Why to use Active Job instead of directly using Third party Background processing
  • Gives the common place to write the jobs
  • We will be able to switch between the queuing backend without having to rewrite the jobs just by changing the queue and backend processing table.
  • Active Job allows your Rails app to work with any one of the backend queue through a single standard interface

  • Even if you aren’t ready to use a queue in your application, you can still use Active Job with the default Active Job Inline backend Jobs enqueued with the Inline adapter get executed immediately.

Active Job adapters Backends Features


|                   | Async | Queues | Delayed    | Priorities | Timeout | Retries |
|-------------------|-------|--------|------------|------------|---------|---------|
| Backburner        | Yes   | Yes    | Yes        | Yes        | Job     | Global  |
| Delayed Job       | Yes   | Yes    | Yes        | Job        | Global  | Global  |
| Qu                | Yes   | Yes    | No         | No         | No      | Global  |
| Que               | Yes   | Yes    | Yes        | Job        | No      | Job     |
| queue_classic     | Yes   | Yes    | Yes*       | No         | No      | No      |
| Resque            | Yes   | Yes    | Yes (Gem)  | Queue      | Global  | Yes     |
| Sidekiq           | Yes   | Yes    | Yes        | Queue      | No      | Job     |
| Sneakers          | Yes   | Yes    | No         | Queue      | Queue   | No      |
| Sucker Punch      | Yes   | Yes    | Yes        | No         | No      | No      |
| Active Job Async  | Yes   | Yes    | Yes        | No         | No      | No      |
| Active Job Inline | No    | Yes    | N/A        | N/A        | N/A     | N/A     |

Resque and delayed Job

  1. Resque supports multiple queues
  2. DelayedJob supports numeric priorities
  3. Resque workers are resilient to memory leaks
  4. DelayedJob workers are extremely simple and easy to modify
  5. Resque requires Redis
  6. DelayedJob requires ActiveRecord
  7. Resque can only place JSONable Ruby objects on a queue as arguments
  8. DelayedJob can place any Ruby object on its queue as arguments
  9. Resque includes a Sinatra app for monitoring what's going on
  10. DelayedJob can be queried from within your Rails app if you want to add an interface

A. Generating a job
     Active Job provides a Rails generator to create jobs
     rails generate job site_subscription_payment
B. Enqueue the Job
    SiteSubscriptionPaymentJob.perform_later subscription_obj
    SiteSubscriptionPaymentJob.set(wait_until:         Date.tomorrow.noon).perform_later(subscription_obj)
    SiteSubscriptionPaymentJob.set(wait: 1.week).perform_later(subscription_obj)
    SiteSubscriptionPaymentJob.perform_later(subscription_obj, company)
C. Job Execution
For enqueuing and executing jobs in production we need to set up a queuing backend Rails itself only provides an in-process queuing system, which only keeps the jobs in RAM. If the process crashes or the machine is reset, then all outstanding jobs are lost with the default async back-end
D. Setting the Backend  config/application.rb
config.active_job.queue_adapter = :delayed_job
E. Starting the Backend
Since jobs run in parallel to your Rails application, most queuing libraries require that you start a library-specific queuing service (in addition to starting your Rails app) for the job processing to work
F. Queues
MyJob.set(queue: :another_queue).perform_later(record)
queue_as :low_priority
Callbacks

Active Job provides hooks during the life cycle of a job. Callbacks allow you to trigger logic during the life cycle of a job.

A. Available callbacks
before_enqueue
around_enqueue
after_enqueue
before_perform
around_perform
after_perform

 before_enqueue do |job|
    # Do something with the job instance
  end

  around_perform do |job, block|
    # Do something before perform
    block.call
    # Do something after perform
  end

Action Mailer
One of the most common jobs in a modern web application is sending emails outside of the request-response cycle
So the user doesn't have to wait on it. Active Job is integrated with Action Mailer so you can easily send emails asynchronously

# If you want to send the email now use #deliver_now
ApplicationNotifier.user_approved(@user).deliver_now

# If you want to send the email through Active Job use #deliver_later
ApplicationNotifier.user_approved(@user).deliver_later






Tuesday, 2 February 2016

Automation Testing Using Rspec and Cucumber In Ruby on Rails

Automation Testing:

1. Unit Test

A unit test focuses on a single “unit of code” – usually a function in an object or module. By making the test specific to a single function, the test should be simple, quick to write, and quick to run. This means you can have many unit tests, and more unit tests means more bugs caught. They are especially helpful if you need to change your code, as you can safely do so and trust that any other code will not break.

2. Integration Test

Multiple pieces are tested together, for example testing database access code against a test database

3. Acceptance test/ Function Test/Automation Test

Automatic testing of the entire application End to End Testing or "Full Application", for example using a tool like Selenium to automatically run a browser.

TDD - Test Driven Development

a. Write Test
b. Write code
c. Run Test
d. Clean up code

Red, Green, Refactor

BDD - Behavior Driven Development

Difference Between TDD and BDD

BDD uses a more verbose style so that it can be read almost like a sentence. BDD is to test the TDD

  1. BDD focuses on the behavioural aspect of the system rather than the implementation aspect of the system that TDD focuses on.
  2. BDD gives a clearer understanding as to what the system should do from the perspective of the developer and the customer. TDD only gives the developer an understanding of what the system should do.
  3. BDD allows both the developer and the customer to work together to on requirements analysis that is contained within the source code of the system.

Webdriver

WebDriver is a tool for writing automated tests of websites. It aims to mimic the behaviour of a real user, and as such interacts with the HTML of the application.

Capybara uses the same DSL to drive a variety of browser and headless drivers
Rack_test
RackTest is Capybara's default driver.
It is written in pure Ruby and does not have any support for executing JavaScript.
Since the RackTest driver interacts directly with Rack interfaces, it does not require a server to be started
If your application is not a Rack application (Rails, Sinatra and most other Ruby frameworks are Rack applications) then you cannot use this driver
you cannot use the RackTest driver to test a remote application, or to access remote URLs (e.g., redirects to external sites, external APIs, or OAuth services)

Selenium
Capybara-webkit
Poltergeist

Rspec

Rspec is a Testing Framework, Rspec stands for Ruby Specification. Rspec is a low level testing, Rspec is very good for unit testing, that is testing models, controllers, views.


Add below code into your gemfile and bundle install or install it by command line
group :development, :test do
  gem 'rspec-rails', '~> 2.0'
end
Or  gem install rspec-rails

Create the Basic Skelton
rails generate rspec:install

Create the RSpec binstub. In short, the binstub will allow you to run RSpec with bin/rspec instead of bundle exec rspec
bundle binstubs rspec-core

Cucumber 
Cucumber is a high-level testing framework which is designed to let you use Behaviour Driven Development (BDD) to create Ruby on Rails applications
Cucumber’s unique feature is that it uses English (or a number of other supported languages) to define an application’s behaviour.
Gherkin is the language that Cucumber understands
It is a Business Readable, Domain Specific Language that lets you describe software’s behaviour withIt Uses the struout detailing how that behaviour is implemented

Feature file consists of the scenario
Step definition consists of the ruby code to pass the scenario


shoulda-matchers

shoulda-matchers lets us spec common Rails functionality, like validations and associations, with less code.
gem 'shoulda-matchers'
bundle install
should validate_presence_of(:firstname)
http://matchers.shoulda.io/docs/v3.1.1/




Factory-Girl

factory_girl is a fixtures replacement with a straightforward definition syntax(i.e Test data)
gem 'factory_girl' and bundle install
Create the directory called factories and define with the filename same as table name
FactoryGirl.define do
  factory :user do
    firstname "satheesh"
    lastname "kumar"
    email "satheeshkumark@gmail.com"
    password "password"
  end
end

@user = FactoryGirl.build(:user)