Thursday, 20 October 2016

What Is Responsive Web Design?

"Responsive web design allows a site’s layout to change as the screen size being used to view that site changes. A wide screen display can receive a site design with multiple columns of content while a small screen can have that same content presented in a single column with text and links that are appropriately sized to be read and used on that smaller display."

So why is responsive web design the most important feature that you can add to your website? Here are 4 key reasons:-

1. Supporting the Multi-Device User2. One Site to Rule Them All3. Improved Search Engine Rankings4. Future Scalability

Conclusion


Every website, regardless of that site’s goals or the audience that it serves, will benefit from a display that works great across different screen sizes and on various devices. By ensuring that responsive web design is feature that you make a priority on all website projects

Monday, 25 July 2016

Align modal window vertically center

Vertically centering Bootstrap modal window

.modal {
  text-align: center;
  padding: 0!important;
}

.modal:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  margin-right: -4px;
}

.modal-dialog {
  display: inline-block;
  text-align: left;
  vertical-align: middle;
}

Tuesday, 19 April 2016

Angular2 And It's Brand New Features

Angular2

About 2 year ago, Google and angular team together made the decision to drastically change the tremendously popular Angular1.x framework(https://docs.angularjs.org).They decide to make better the framework by reducing the learning curve and providing performance enhancements.

Angular 2.0 beta version was officially announced in 15 December, 2015. This version do not have complex major update, rather a rewrite of the entire framework and will include breaking changes!.For more information please visit: https://angular.io/ 

Why Angular2?

Let’s briefly consider the philosophy behind the new version. Angular 2.0 development was started to address the following concerns:

1)Typescript:
The new version of angularjs written in EC6(JavaScript next version) and uses typescript rather then plain java script. The previous versions of ECMAScript defines everything as a prototype. Now ES6(next JavaScript version) allow classes , which make code more readable as Rails, java code.
Typescript is an extension of ECMAScript, in fact:
Typescript = ES6 + Types + Annotations

Because Angular2 uses Typescript, the functionality of Typescript itself and its libraries can be used. Angular2 is just a framework which couples different features. Other libraries can easily be used. For example:
MongoDB interface because it already has a connector in Typescript.
Web-sockets is another feature that is not directly something from Angular2, but it can easily be implemented and support has been added to the specification.

2)Performance:

Angular team keep in mind the better performance target while working on that, So they make some changes or can say lot of changes in existing angular as:

1)Goodbye to Controllers & $scope:
Even though ‘$scope’ has been replaced by “controller as” as a best practice since Angular 1.2, it still lingers in many tutorials. Angular 2 finally kills it off, as properties are bound to components. Instead of using controllers, Angular2 bet on component-based UI, similar to ReactJS. The core team dropped controllers but added components and kept the directives.

Angular 1.x:

angular.module(‘example’) .controller(‘ExampleCtrl’, function($scope) {
  $scope.name = “John Smith”;
});

Angular 2.0:

@Component({ selector: 'example' })
@View({ templateUrl: './components/example/example.html' })
export class Example {
  constructor() {
    this.name = “John Smith”;
  }
}

$scope has removed in Angular 2.0 in favor of ES 6 classes. It removed due to late change detection.

2)No Two-Way data-binding:
  Removing the two-way data-binding leads to:
  ~ More explicit data-flow
  ~ No circular dependencies between bindings.

3) Web Components (Component Based UI):

Generally WC are set of standard that allow for the creation of reusable widgets or components in web documents and web applications.
Angular2 is adopting a component-based UI, a concept that might be familiar to React developers. The Angular 1.x controllers and directives blur into the new Angular 2 Component.

5) Ultra Fast Change Detection:

As currently angular 1.x uses $scope which sometimes unable to digest the changes and apply over view.So as I describe above angular2 team remove the $scope and they took a new concept, which generate JavaScript classes and implement this change detection mechanism, instead of using method calls.

6) Mobile First:

Angular was implemented in frameworks like Ionic in a hard manner which was detrimental to the user’s experience and performance of the application in general.

With all this terrible experience, Angular 2 was designed to be better and ready for any thing coming its way that is mobile oriented.

7)Errors in the Template Expressions:

One thing I do not really like about angularjs 1.x is appropriate error messages. The errors, which you were supposed to get were omitted and you weren’t aware that your code actually doesn’t work. Well, in Angular2 we will get run time errors in such cases.

Angular 2.0 will contain a logging service called diary.js—a super useful feature which measures where time is spent in your application.

Conclusion:

Angular2 is a brand new framework, which is not backward compatible with AngularJS 1.x. It is implemented in Typescript but you don’t have to use it if you don’t want to. It implements some of the ideas from ReactJS, mostly the unidirectional data flow, which makes it work great with the flux architecture. It is on top of web standards (which is a big bonus compared to other framework) and takes advantage of some of the web components’ APIs. It will be much faster and lighter compared to AngularJS 1.x and will be supported by the modern browsers with polyfills. Currently no stable version for Angular2 avilable right now.

The API of Angular2 is still under development. There are a lot of things, which are still not clarified (like change detection, best API, forms API, etc.). 

Saturday, 2 April 2016

Setup Nginx with Puma on Ubuntu



Hope you enjoyed our previous blog for setting up the rails app using Nginx and Unicorn .
In this series, today we are going to cover Puma . Puma has gained quite popularity among rails developer in recent time so we thought, its worth writing about puma as Rails Developer. 

Why Puma ??


As the rails framework got matured over the time, its app servers also got evolved. There are couple of options available when you look for deploying your rails app. Passenger, Unicorn, Thin and Puma. Puma got quite popular over last year. Heroku also recommend using puma for its Cedar platform.
Puma is fast, threaded and highly concurrent server. For best throughput it is recommend to use Ruby implementation with real thread like Rubinius or JRuby. You can scale puma on thread level as well as worker level.

For a quick look about puma's comparison with its other counterparts, visit http://puma.io/ .

Lets Start...


Prepare your instance/server for deployment. 

Please follow below steps from our previous blog as they are not worth repeating here. 

Prepare your instance & Install dependent libraries
Install Nginx
Install Ruby

Puma

Add puma to your Gemfile  and run bundle install 

gem 'puma'

Add puma.rb in config/ directory of your application.


environment 'production'

daemonize true
workers 2

threads 0,8

bind  "unix://your/app/path/tmp/puma.sock"
pidfile "/your/app/path/tmp/pids/puma.pid"

preload_app!

on_worker_boot do

  ActiveRecord::Base.establish_connection

end



You are probably using capistrano or mina to automate your deployment. If so in that case please put puma.rb in shared/config  and make sure your to create symbolik link in deployment script. I should probably have a separate blog for automating deployment. 


Configure Nginx to use Puma



upstream your_app {
    # Path to Puma SOCK file, as defined previously
    server unix://your/app/path/tmp/puma.sock;
}

server {

    listen 80;
    server_name yoursite.com;

    # Application root, as defined previously
    root /your/app/path/public;

    try_files $uri/index.html $uri @app;

    location @app {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass http://your_app;
    }

    error_page 500 502 503 504 /500.html;

  
}  


Start Puma

Considering you have adjusted db setting in config/database.yml and all other environment related changes, its time to start puma. Lets do it .

From root of your application directory, run below


bundle exec puma -C config/puma.rb



Its time to visit your site. Enjoy simple, fast, threaded and concurrent PUMA!!!!!!!!!




Monday, 7 September 2015

On-Boarding Feature Of Stripe

When User Wants to create Instant account for Payment Process On Stripe, And App Owner wants to add new user under his Current Stripe Account to manage all his app users.

Step 1 :- To Start this, We need a client_id from stripe account. below the screen shot from when we can get client Id in Stripe account dashboard.

Stripe Dashboard => Account Setting => Connect tab => Client Id



Step 2 :- Now add this Client Id in below link where you want to add on-boarding link.

https://connect.stripe.com/oauth/authorize?response_type=code&client_id=client_id&scope=read_write

This above link will take user to Stripe On-boarding Form, From where user need to fill all the info related to stripe account.


Step 3 :- Now, The user will then be redirected back to your site (specifically to your redirect_url), passing along either an authorization code or an error ( if the connection request was denied)
So For this, we need to add redirect url into our stripe account. See Below :

Stripe Dashboard => Account Setting => Connect tab => Redirect URLs: 


Dynamically Setting the redirect URI 


For security purposes, Stripe will only redirect a user to a pre-defined uri. However, Connect allows you to define more than one redirect URI, which can be used to further customize the user's experience. For example, you could have some of your users redirected back to "https://sub1.example.com" and others sent to "https://sub2.example.com", each with custom behavior.

First, In Your platform setting (Stripe Dashboard => Account Setting => Connect tab => Redirect URLs:), set the redirect URIs to a comma-separated list of allowed URIs. Second, add a redirect_uri parameter to your authorization request with a value found in your comma-separated list.

https://connect.stripe.com/oauth/authorize?response_type=code&client_id=client_id&scope=read_write&redirect_uri=custom_redirect_uri


Step 4 :- After the user has connected

When the user arrives at Stripe, they'll be prompted to allow or deny the connection to your platform, and will then be sent to your redirect_uri page. In the URL, Stripe will pass along an authorization code:

your_redirect_uri?scope=read_write&code=AUTHORIZATION_CODE

Step 5 :- Get Stripe Credentials from authorization code

api_key = Secret Key ( Stripe Dashboard =>Account Setting => Api Keys)

client_id = client id ( Stripe Dashboard => Account Setting => Connect => Client Id )


options = {:site => 'https://connect.stripe.com', :authorize_url => '/oauth/authorize', :token_url =>'/oauth/token', :raise_errors => false}

client = OAuth2::Client.new(client_id, api_key, options)  ( For this you will need to add oauth2 gem in your gemfile)

resp = client.auth_code.get_token(AUTHORIZATION_CODE, :params => {:scope => 'read_write'})

Stripe will return a response containing the authentication credentials for the user :

{
  "token_type": "bearer",
  "stripe_publishable_key": PUBLISHABLE_KEY,
  "scope": "read_write",
  "livemode": false,
  "stripe_user_id": USER_ID,
  "refresh_token" : REFRESH_TOKEN,
  "access_token" : ACCESS_TOKEN
}

and if there was a problem, they'll instead an error.

{
  "error": "invalid_grant",
  "error_description": "Authorization code does not exist: AUTHORIZATION_CODE"
}


Stripe provided some more options in this on-boarding process. Use below link for your extra need in app.

https://stripe.com/docs/connect/standalone-accounts#deferred-accounts







Monday, 17 August 2015

Shell script to kill Zombie process

Zombie process is a process state when the child dies before the parent process.

To see zombie process:
Run “ps aux” and look for a Z in the STAT column.
It also indicates as  “<defunct>” after the process information when we run “ps -aef”.

here is the link to get complete details of Zombie process.
https://zombieprocess.wordpress.com/what-is-a-zombie-process/

Shell script to stop all Zombie process:

We can find and remove all zombie process from our Linux system.
http://www.linuxscrew.com/wp-content/uploads/2007/09/zombies.sh.txt

Shell script to stop Specific Zombie process: 

We can also find and remove specific zombie process, in my case I am using thinking sphinx and below is the shell script to find and stop sphinx zombie process:


#!/bin/bash

release_path() {
  cd <application current path>
}

stat=`ps ax | awk '{print $1}' | grep -v "PID" | xargs -n 1 ps lOp | grep -v "UID" | awk '{print"pid: "$3" *** parent_pid: "$4" *** status: "$10" *** process: "$13}' | grep ": Z.*searchd"`

if ((${#stat} > 0));then
  ps ax | awk '{print $1}' | grep -v "PID" | xargs -n 1 ps lOp | grep -v "UID" | awk '{print"pid: "$3" *** parent_pid: "$4" *** status: "$10" *** process: "$13}' | grep ": Z.*searchd" | awk '{print $5}' | xargs -n 1 kill -9
  echo `date`" ::: killed thinking sphinx zombie process!" >> /var/log/zombies.log
  
  sphinx_stat=`ps ax | awk '{print $1}' | grep -v "PID" | xargs -n 1 ps lOp | grep -v "UID" | awk '{print"pid: "$3" *** parent_pid: "$4" *** status: "$10" *** process: "$13}' | grep ": Sl.*searchd"`

  if ((${#sphinx_stat} > 0));then
    ps ax | awk '{print $1}' | grep -v "PID" | xargs -n 1 ps lOp | grep -v "UID" | awk '{print"pid: "$3" *** parent_pid: "$4" *** status: "$10" *** process: "$13}' | grep ": Sl.*searchd" | awk '{print $2}' | xargs -n 1 kill -9
  fi
  
  release_path
  RAILS_ENV=production <run your rails specific command>
fi
 

Above script will find the sphinx zombie process and then kill that process, after that we are finding the sphinx process that is still running and kill that process as well.
You can also run your rails specific command in that file.

Run your shell script:

Save this file with extension “.sh” and give it permission “chmod +x <file name>.sh”, and put this file to specific folder.

You can directly run this script by the command on the file directory “./<file name>.sh

Or you can add this shell script to your crontab file.


Thanks!

Friday, 31 July 2015

Rails 4 ENUM Feature

I know we all are aware about all the major upgrades with Rails 4, like concerns, decorator, presenter, strong parameter etc. and have started using them pretty well but there is an another really great feature introduced with Rails 4 ActiveRecord is ENUM module that we may not have given much attention to.

So let me introduce you with this power of Rails 4:

We often need an attribute in model where we want to save some kind of STATUS for that particular record, and this is where we can use this feature in our application.

Let me explain you the clear difference between the implementation in Rails 3 & Rails 4 with an example.
 

Rails 3 implementation :


class Order < ActiveRecord::Base
# schema change may look like this:
# add_column :orders, :status, :string
  
  STATUS = ["request", "processing", "shipping", "done"]
  
  scope :status, -> (status) { where status: status }
end

order = Order.last
order.update(status: Order::STATUS[0]) # => true

order.status # => "request"

Order.status("request") # => a scope to find all orders with "request" status

Rails 4 implementation :


class Order < ActiveRecord::Base
# schema change may look like this:
# add_column :orders, :status, :integer, default: 0 # defaults to the first value (i.e. "request")
  
  enum status: ["request", "processing", "shipping", "done"]
  
end

order = Order.last
order.update(status: "request") # => true

order.status # => "request"

order.request? # =>  check if status is "request"

order.request! # =>  update! the order with status set to "request"

Order.request # => a scope to find all orders with "request" status


Internally these states are mapped to integers in the database to save space. Also its worth mentioning here that methods added by enum saves us from writing scopes and methods to do above such operations.


There is a lot new features introduced with Rails 4 in developers benefit, this is one of them I though to share.

Happy Reading... :)