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.

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 "" and others sent to "", 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.

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:


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 => '', :authorize_url => '/oauth/authorize', :token_url =>'/oauth/token', :raise_errors => false}

client =, 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.

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.

Shell script to stop all Zombie process:

We can find and remove all zombie process from our Linux system.

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:


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
  RAILS_ENV=production <run your rails specific command>

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.


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 }

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"]

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... :)

Friday, 12 June 2015

IOS:Apple Pay Integration

 Apple Pay (Apple payment gateway integration)

Apple Pay is a mobile payment technology that lets users give you their payment information for real-world goods and services in a way that is both convenient and secure.Here some step (what would be need to Apple Pay integration) are mention above steps to integrate Apple Pay in your app. 

Step 1 - Configuring Your Environment

A merchant ID identifies you to Apple Pay as being able to accept payments. The public key and certificate associated with your merchant ID is used as part of the payment process to encrypt payment information. Before your app can use Apple Pay, you need to register a merchant ID and configure its certificate.

- To register a merchant ID

In Member Center, select Certificates,Identifiers & Profiles. 
Under Identifiers, select Merchant IDs
Click the Add button (+) in the upper-right corner.
Enter a description and identifier, and click Continue.
Review the settings, and click Register.
Click Done.

-To configure a certificate for your merchant ID

In Member Center, select Certificates,Identifiers & Profiles.
Under Identifiers, select Merchant IDs
Select the merchant ID from the list, and click Edit.
Click Create Certificate, follow the instructions to obtain or generate your certificate signing request (CSR), and click Continue.
Click Choose File, select your CSR, and click Generate.
Download the certificate by clicking Download, and click Done.

If you see a warning in Keychain Access that the certificate was signed by an unknown authority or that it has an invalid issuer, make sure you have the WWDR intermediate certificate - G2 and the Apple Root CA - G2 installed in your keychain. 

To enable Apple Pay for your app in Xcode, open the Capabilities pane. Select the switch in the Apple Pay row, and then select the merchant IDs you want the app to use.

Step 2 - Setting Up

Apple Pay uses the PassKit framework, so you’ll need to be sure to include this in your project and import it into the necessary files.

#import <PassKit/PassKit.h>

You’ll also want to receive callbacks when Apple Pay processes information, so be sure to add the delegate to the receiving class:

@interface ViewController : UIViewController <PKPaymentAuthorizationViewControllerDelegate>

Step 3 - Create Payment Request

You’ll want to be sure to check whether or not the device will handle payments, which you can do with the code here:

if([PKPaymentAuthorizationViewController canMakePayments]) { ... }

Within that block, you can create a payment request using the `PKPayment` class. Modify this information as needed (make sure your `merchantIdentifier` matches the one you created in the previous step!).

PKPaymentRequest *request = [[PKPaymentRequest alloc] init];

        request.countryCode = @"US";
        request.currencyCode = @"USD";
        request.supportedNetworks = @[PKPaymentNetworkAmex,           PKPaymentNetworkMasterCard, PKPaymentNetworkVisa];
        request.merchantIdentifier = @"";
        request.merchantCapabilities = PKMerchantCapabilityEMV;

Step 4 - Add Items To Payment

You can create items to display using the `PKPaymentSummaryItem`. This object represents an item and a price. The last object in the array must be the total value.

 PKPaymentSummaryItem *widget1 = [PKPaymentSummaryItem summaryItemWithLabel:@"Widget 1"  amount:[NSDecimalNumber decimalNumberWithString:@"0.99"]];
PKPaymentSummaryItem *widget2 = [PKPaymentSummaryItem summaryItemWithLabel:@"Widget 2"  amount:[NSDecimalNumber decimalNumberWithString:@"1.00"]];
PKPaymentSummaryItem *total = [PKPaymentSummaryItem summaryItemWithLabel:@"Grand Total"amount:[NSDecimalNumber decimalNumberWithString:@"1.99"]];

request.paymentSummaryItems = @[widget1, widget2, total];

Step 5 - Present the Authorisation view controller

Finally, present the view controller that is provided by the PassKit framework. This will take care of the authorisation.

PKPaymentAuthorizationViewController *paymentPane = [[PKPaymentAuthorizationViewController alloc] initWithPaymentRequest:request];
 paymentPane.delegate = self;
 [self presentViewController:paymentPane animated:TRUE completion:nil];

Step 6 - Implement delegate methods

After the framework displays the transaction’s status, the authorisation view controller calls your delegate’s paymentAuthorizationViewControllerDidFinish: method. In your implementation, dismiss the authorisation view controller and then display your own app-specific order-confirmation page.

(void)paymentAuthorizationViewControllerDidFinish: (PKPaymentAuthorizationViewController *)controller

When the user authorises a payment request, the framework creates a payment token by coordinating with Apple’s server and the Secure Element, which is a dedicated chip on the user’s device. You send this payment token to your server in the paymentAuthorizationViewController:didAuthorizePayment:completion: delegate method, along with any other information you need to process the purchase

- (void)paymentAuthorizationViewController:(PKPaymentAuthorizationViewController *)controller
 didAuthorizePayment:(PKPayment *)payment completion:(void (^)(PKPaymentAuthorizationStatus status))completion

Saturday, 6 June 2015

Different ways to early returns from controllers

In some scenarios we don't need to execute full code of a controller method and want to return in-between.
So Here are different ways to early return from the controller methods :

1) redirect_to path and return

class Controller1 < ApplicationController
  def method1
    if something
      redirect_to edit_x_path(@object) and return

    if something_else
      redirect_to index_path(@object) and return
    # Code
    # Code

It is the classic way. It is working properly If all redirects and return are in same method. If we call method2 in our method1 and try to redirect and return from method2, then it will give double render or redirect error.

So here are another ways to handle above scenario.

2) Extracted method return with AND

class Controller1 < ApplicationController
  def method1
    method2 and return
    # even more code over there ...


  def method2
    unless @var.some_condition? 
      redirect_to edit_x_path(@var) and return true

    if some_condition_x?
      redirect_to y_path(@var) and return true

In this technique we need to write return true instead of only return. If you forgot to write true  
It can cause issue.

3) Extracted method return with OR

class Controller1 < ApplicationController
  def method1
    method2 or return
    # even more code over there ...


  def method2
    unless @var.some_condition? 
      redirect_to edit_x_path(@var) and return 

    if some_condition_x?
      redirect_to y_path(@var) and return 
  return true

In this case we must need to add return true at the end.

4) Extracted method return via yield

class Controller1 < ApplicationController
  def method1
    method2  {return}
    # even more code over there ...


  def method2
    unless @var.some_condition? 
      redirect_to edit_x_path(@var) and yield 

    if some_condition_x?
      redirect_to y_path(@var) and yield 

We can say it explicit return. It depends on callback block. If callback block contains {return} then it will perform early return.

5) Return with performed? method

class Controller1 < ApplicationController
  def method1
    method2; return  if performed?
    # even more code over there ...


  def method2
    unless @var.some_condition? 
      redirect_to edit_x_path(@var) and return 

    if some_condition_x?
      redirect_to y_path(@var) and return 

performed? method is define in ActionController::Metal controller. Using this method we can test whether  render or redirect already performed. 

Monday, 1 June 2015

Disadvantages of creating excess instance variables

As we have heard that "creating unnecessary or excess instance variables is a bad practice."
but I don't understand why is it so, I started searching about this but couldn’t found a meaningful stuff, then I Dig a bit deeper and found that

As the number of instance variables increase there is a small increase in response time of application.

"A Rails view doesn’t have direct access to its controller’s instance variables."

After reading this a question arises "Then how can we access then controller's instance variable in view ??"

let me explain it: The source says that "The controller’s variables are transferred to the view renderer." which means all instance variables will be copied from the controller to the view you are using them or not, this process takes some CPU cycles which increases the response time of application by a time interval.

The Best practices say that we should have view with only a single instance variables as maintaining a single instance variable is simpler and easier

Tuesday, 19 May 2015

Unit test cases for AngularJs app using Karma and Jasmine testing framework


Require Files: [angular.js, angular-mock.js, karma, karma-jasmine, karma-chrome-launcher]
configuration file: karma.conf.js (we can create it manually or via command karma init)

Karma is spectacular test runner for JavaScript, runs on Node.js and is available as a NPM package. Above all require files are available as an NPM package. To run test cases you just have to run command karma start karma.conf.js 
include all files in karma.conf.js as file option for which you wanted to write test cases.

I created a first test case for directive "CompareTo" define in "motorbot.reservation.directives". Here is code
in directives/reservationsDirective.js:

 var directives = angular.module("motorbot.reservation.directives", []);
 var compareTo = function() {
   return {
     require: "ngModel",
     scope: {
       otherModelValue: "=compareTo"
    link: function(scope, element, attributes, ngModel) {
      ngModel.$validators.compareTo = function(modelValue) {
        return modelValue == scope.otherModelValue;

      scope.$watch("otherModelValue", function() {
directives.directive('compareTo', compareTo);

This directive is use on view to compare password and password-confirmation:

 <input  type="password" class="form-control" name="user_password_confirmation" compare-to="patron.password" ng-model='patron.password_confirmation' required />

Here is test case for directive "compareTo" in test/directives/directiveSpec.js:

  describe('Directives', function() {
    //include modules
    describe('testing directive compare to', function() {
      var $scope, element, scope;
      var html = '<input compare-to="password" ng-model="password_confirmation"/>';
      // Injecting angular services in unit test for this we need angular-mock.js
      beforeEach(inject(function($rootScope, $compile) {
        $scope = $rootScope;

        // load the values to send
        $scope.password = 'abc';
        $scope.password_confirmation = 'abc2';

        // create the element and compile it
        element = angular.element(html);

        // get the scope of this directive
        scope = element.scope();
      it("should not valid password_confirmation", function() {
      it("should valid password_confirmation", function() {
        $scope.password_confirmation = 'abc';

Here is sample for karma.conf.js file:

  // Karma configuration
  // Generated on Thu May 14 2015 18:59:11 GMT+0530 (IST)

  module.exports = function(config) {

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: './',

    // frameworks to use
    // available frameworks:
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    // list of files for which you wanted to write test cases
    files: ['bower_components/angular/angular.js',

    // list of files to exclude
    exclude: [

    // preprocess matching files before serving them to the browser
    // available preprocessors:
    preprocessors: {

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters:
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN    || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers:
    browsers: ['Chrome'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false

git–push large commits over http fail

Problme, exception, Error: git–push large commits over http fail

If you are facing this issue with git:

error: RPC failed; result=22, HTTP code = 413
fatal: The remote end hung up unexpectedly
fatal: The remote end hung up unexpectedly
Everything up-to-date
If we made commit with large files size or large amount of data in a single commit, then it may cause that error.
This issue might also come with HTTP github repository url, that we are using to clone the repo.

We can increase buffer size to solve large amount of data issue or increase the nginx buffer size by the parameter "client_max_body_size".

If we don't have large amount of data and still we are facing this issue, so replace your github HTTP protocol with SSH protocol or replace HTTP to HTTPS in that url.

Friday, 8 May 2015

Shaping up with angularjs

Here we find angular challenges on different levels. It is good for  angular beginner to enhance
their skills :

By clicking "start course" you can start with challenges. For completing challenges you will achieve points as well.

Wednesday, 22 April 2015

IOS : Automation Testing

For creating IOS automation test script use below links and i have also attached sample code that will tell you how in write and how to use automation script in IOS.

IOS : Watch Kit

There are few links to give information about how to code for iWatch.

Function by which watch app communicate with iPhone app

# Write function in WKInterfaceController

WKInterfaceController.openParentApplication(param, reply: { (replyValues, error) -> Void in }

//param is value to send 
// replyValues is result which we get

# Write method in iOS app appDelegates

func application(application: UIApplication!, handleWatchKitExtensionRequest userInfo: [NSObject : AnyObject]!, reply: (([NSObject : AnyObject]!) -> Void)!) {
    // retrieved parameters from Apple Watch

    // pass back values to Apple Watch
    var retValues = Dictionary<String,String>()

    retValues["retVal1"] = "return Test 1"
    retValues["retVal2"] = "return Test 2"


# Add group Id in Your app Provision Profile 

Going to Provision portal,identifiers->App IDs, your id, edit, app groups enable, edit set app group and save. Now go to provision profile and re-generate all the inactive Provision profiles and download them.

Monday, 20 April 2015

Grep Ruby: Configure Nginx with Unicorn on Ubuntu(Linux)

Grep Ruby Practices: Configure Nginx with Unicorn on Ubuntu(Linux): Introduction So finally you choose to go with  Nginx +  Unicorn for your rails application.  Thats great! We will go through with all...

Friday, 17 April 2015

Absolute URL / Full URL in Rails 4

Rails 4


def absolute_url
  request.base_url + request.original_fullpath

Action Mailer Notable changes in 4.2 release:

  • link_to and url_for generate absolute URLs by default in templates, it is no longer needed to pass only_path: false. (Commit)

If you use the _url suffix, the generated URL is absolute. Use _path to get a relative URL.

<%= link_to "User Home", user_url %>

Thursday, 16 April 2015

Highlite your code for your blog

So you wanted to highlight your code for your blog ?

Nice looking code snippet is always important for you technical blog. For example you have below code

  def manager?
    role.downcase == "manager"

  def bidder?
    role.downcase == "bidder"

That doesn't look good at all.

Here are the pretty version of above code

  def manager?
    role.downcase == "manager"
  def bidder?
    role.downcase == "bidder"

Isn't it good?

Yes it is. You can use online tool to highlight your code. does pretty nice job.
Keep using it.


Wednesday, 15 April 2015

Way to clean up gem OR remove old versions to keep the most recent

Way to clean out any old versions of gems.

    > sudo gem cleanup

If you just want to see a list of what would be removed you can use:

    > sudo gem cleanup -d

You can also cleanup just a specific gem by specifying its name:

    > sudo gem cleanup gemname

for remove specific version like 1.1.9 only

   >  gem uninstall gemname --version 1.1.9

If you still facing some exception to install gem, like:

invalid gem: package is corrupt, exception while verifying: undefined method `size' for nil:NilClass (NoMethodError) in /home/rails/.rvm/gems/[email protected]/cache/nokogiri-

the, you can remove it from cache:

    > rm /home/rails/.rvm/gems/[email protected]/cache/nokogiri-

Friday, 10 April 2015

With running Rspec my Ubuntu 14 incredibly slow

The ext4 or fourth extended filesystem is a journaling file system for Linux

As I found, Ubuntu and ext4 partitions dont work good together - I don't know why :(

What I found a way to fix it:

> sudo vi  /etc/fstab

Previously it was following:

UUID=7d4ba8b6-8c0f-493a-bcc7-6d2230ce217a /               ext4   errors=remount-ro 0       1

I did add barrier=0 in following way
UUID=7d4ba8b6-8c0f-493a-bcc7-6d2230ce217a /               ext4   barrier=0,errors=remount-ro 0       1

After above changes in file then:

Restart and run rspec again. If it works then You should see a difference

Also It helps with Ubuntu 14 and Rails 4, Selenium+Capybara tests (no Rspec)

Thursday, 9 April 2015

PhantomJS and setup steps on linux Ubuntu 14.04.1

What is phantomjs!

Full web stack and No browser required

PhantomJS is a headless WebKit scriptable with a JavaScript API. 

> sudo apt-get install phantomjs

> phantomjs --version
-bash: /usr/local/bin/phantomjs: No such file or directory

>  whereis phantomjs
phantomjs: /usr/bin/phantomjs /usr/lib/phantomjs /usr/bin/X11/phantomjs

> sudo ln -s /usr/bin/phantomjs /usr/local/bin/phantomjs

Check If it works:
> phantomjs --version

That's all!

Monday, 6 April 2015


Ruby on Rails (RoR) is very popular Web application frameworks. It is easy for developers to compare Ruby on Rails with other frameworks.
Let’s look at basic differences between Ruby and other languages, below comparison give a simple idea to advantages and disadvantages in Web development:
Ruby vs PHP:
  • A PHP code can executes faster than a RoR code. but a Ruby on Rails application has fewer lines of coding as compared to the same complex application written in PHP :(
  • Ruby on Rails applications works well with UNIX-based server
  • TDD/BDD with test suite code in Ruby on Rails application is simple and fast. In PHP, testing modules and coding is a bit difficult and not easy to understand as compare to rails.
  • RoR application has a clear code structure(mvc) than PHP
  • few frameworks like Zend, Codeigniter, and CakePHP support PHP. In the same way, Vintage, Sinatra and Rails support Ruby.
  • PHP requires less memory space than Ruby. Therefore, PHP applications generally run faster than Ruby on Rails applications.
  • .
  • .
  • .
  • .....