An Introduction to Rails API


API stands for Application Interface Program, which provides one application to interact with ‘n’ number of applications which is of same/different language, to access the data/functionality.
Creating API application provides more scalability to the web applications. It will also helps for the easy integration with cross domain applications/languages.
• iOS apps
• Android apps
• Node js framework
• Angular js framework

There are 2 ways to achieve this in rails.

1. We can easily create a new API application using gem called rails-api, which inherit the application from ActionControllerAPI instead of ActionControllerBase and it will skip view generation. This will also helps to configure the middlewares.

2. In case the application is already created we have to inherit ActionControllerAPI manually.

Basic Flow

railscarma_Api

Versioning API’s
Once the application is set-up we can create the controller under controller/v1 folder, that will helps for the easy maintenance of versions and releasing new version of API’s.

In this controller we can write code for crud or some functionality that can be called by curl or as API request from front end application for the GET, POST, DELETE, PATCH requests gives responses in JSON/xml format, which is in human readable form. This json data can be read and shown from front-end application.

Security
By passing the token which is generated for each user and email of the user through an api header to secure an api. It can be ensured that there only authenticated user can access and modify data using api.

Using these we can authenticate the user and secure the application. According to the data sent and the data matches in the applications we can send the proper responses back to the front-end application.

These are few basic aspects which can be implemented using rails and create a robust API architecture.

Integrating Paypal into Rails Application


Paypal is an e-commerce based web application, which transfers the amount between two accounts. Almost all US-based companies use paypal for there receiving and doing the payments.Lets see how to integrate this service in rails application in different steps.

Note: I have tried these steps in development mode, on my local machine. It works fine but haven’t tested in production.

Step 1: a> In case if one doesn’t have a paypal account, you can visit http://developer.paypal.com and sign up to make an account. Then login using that account.

b> In order to test the application user should have test accounts on paypal. For e,g – I made two accounts, one as buyer and another as seller. Both have there secure login and later they can use these accounts to send or receive payments.

c> These pre-configured accounts can be created by going to test accounts tab.Then click on pre-configured option to create test accounts on paypal with little extra information.Please make note of the account id and password generated for both buyer and seller.

d> Now based on requirement check the checkbox of the particular account and click on the link box to enter that particular test account. Clicking on that will redirect you tohttp://sandbox.paypal.com. Using your account information u one can login to that particular account.These accounts and payments are simulated as any original account will behave.

e> Now lets code our rails application to use these accounts.I am using “Add to cart”option to select few items and add them into cart, by clicking on checkout button, it redirects to paypal site.

On Next Page:

f> In my cart.rb,paypal_url method to redirect to paypal site:

def paypal_url(return_url,notify_url) #1st url to return to ur own app,2nd url for paypal to send notification values = { :business => ‘dhyanb_1326716016_biz@gmail.com’, #account generated by paypal :cmd => ‘cart’, :upload => 1, :return => return_url, :invoice => id, :notify_url => notify_url } line_items.each_with_index do |item, index| values.merge!({ “amount#{index+1}” => item.product.price, “item_name_#{index+1}” => item.product.title, “item_number_#{index+1}” => item.product.id, “quantity_#{index+1}” => item.quantity }) end “https://www.sandbox.paypal.com/cgi-bin/webscr?” + values.to_query end

g> In my show.html.erb, I have placed the checkout button with url to return to:
<?php
= button_to “Checkout”, @cart.paypal_url(products_url,payment_notifications_url)
?>

h> You need to be logged in while simulating this service.

i> After clicking on checkout, this will redirect to Paypal site with secure connection.

This will look like this: It contains cart details and form for buyer to log in.

j> On this payment page, one needs to give his buyer account id and password to log in. After logging in it will display other user details too with pay-now option.After paying the, the buyer can return to his own store by clicking on the link provided on the page.

Notifications from Paypal

a> Notifications sent from paypal can be saved in the database.For that we need to have model with proper fields. i.e- rails g model Payment Notification params:text status:string transaction_id:string cart_id:integer

My notifications controller (create method) will look like this:-

def create PaymentNotification.create!(:params => params, :cart_id => params[:invoice], :status => params[:payment_status], :transaction_id => params[:txn_id]) render :nothing => true
end

b> There is no direct of testing this,unless deployed in production but it can be tested in the console using curl command. eg-curl -d “txn_id=9JU83038HS278211W&invoice=1&payment_status=Completed”http://localhost:3000/payment_notifications

c> If this command runs without giving any exceptions, then all is well and values will be stored in the database.

Start making payment now.

Thanks for reading !!!

Source: RailsCarma

How To Set Up A Rails Application On Main Domain With Passenger?


Upload your application to the server using either ftp/sftp or SSH or if you have your application under version control, checkout or clone your application to a folder in your home directory.

–Next, we need address apache/passenger about your application, this is done by setting a symbolic link from your public_html directory to your applications public directory. Here in the following example my application name is “myapp”.

For example, if your application is in myapp then you would issue the following commands in an SSH session: (Make sure there is nothing you need in your /public_html directory as the following will remove everything in that directory)

rm -rf ~/public_html ln -s ~/myapp/public ~/public_html

–Now we need to enable passenger, this is done by creating a file called .htaccess in your application public directory. Add the following entries in the file ./public/.htaccess under the location of your application root.

RAILS-2.x.x

RailsBaseURI / PassengerAppRoot /home/myusername/myapp

RAILS-3.x.x

RackBaseURI / PassengerAppRoot /home/myusername/myapp –Next, Setup your database and a database user in cPanel, and update your config/database.yml with this new database name, user, and password.

–Migrate or import your database(The command to do this is “rake db:migrate” from your application root path)

–Make sure any third party gems you need are installed, you can view the gems installed by running gem list—local , if there is a gem missing, email support to request the gem to be installed.

You will now be able to access your rails application at your domain, if there are any deployment errors, passenger will display an error message which should help you determine how to fix the error.

 

Source: RailsCarma

How To Setup Nginx On Server For Rails Application?


How To Setup Nginx On Server For Rails Application?Ruby on Rails is a popular rapid development web framework. It allows web designers and developers to quickly implement dynamic and fully featured Ruby on Rails application. This article describes procedures for installing Ruby on Rails in conjunction with the nginx setup and Passenger module.

Nginx (pronounced “engine X”) is a lightweight, high-performance Web server/reverse proxy and e-mail (IMAP/POP3) proxy. It is licensed under a BSD-like license. It runs on UNIX, GNU/Linux, BSD variants, Mac OS X, Solaris, and Microsoft Windows .  Unlike traditional servers, it doesn’t rely on threads to handle requests.

Instead it uses a much more scalable event-driven (asynchronous) architecture. This architecture uses small, but more importantly, predictable amounts of memory under load.

Even if you don’t expect to handle thousands of simultaneous requests, you can still benefit from its’s high-performance and small memory footprint. It scales in all directions: from the smallest VPS all the way up to clusters of servers.

To install nginx you would require passenger first:

Install passenger:

$ gem install passenger

$ passenger -v

In order to let Passenger install it, you need to install a dependency first.

$ sudo apt-get install libcurl4-openssl-dev

use rvmsudo than regular sudo to install it

$rvmsudo passenger-install-nginx-module

start nginx

$ sudo /opt/nginx/sbin/nginx

Configuration

$ sudo nano /opt/nginx/conf/nginx.conf (VPS)

$ sudo /etc/init.d/nginx reload (VPS)

configuration file example

server {

listen 80;

server_name http://www.yourdomain.com;

root /home/Nagakiran/test_app/current/public;

passenger_enabled on;

#charset koi8-r;

#access_log logs/host.access.log main;

#location / {

# root html;

# index index.html index.htm;

#}

Source : RailsCarma

Testing Rails 3.2.3 Application Using Cucumber (BDD)


What is Cucumber?

Cucumber is used for Behavior Driven Development. Cucumber lets software development teams describe how software should behave in plain text. The text is written in a business-readable domain-specific language and serves as documentation, automated tests and development-aid – all rolled into one format.

Cucumber works with Ruby on Rails, Java, .NET, Flex or web applications written in any language. It has been translated to over 40 spoken languages. Cucumber also supports more succinct tests in tables – similar to what FIT does.

Ruby_on_Rails_logo

Install cucumber for Rails 3:

Install Cucumber, Rspec-rails and capybara gem

sudo gem install cucumber-rails
sudo gem install database_cleaner
sudo gem install rspec-rails
sudo gem install capybara
  • Cucumber is a behavior driven development (BDD) framework in particular good for integration and functional tests

  • RSpec is a behavior driven development (BDD) framework for low-level testing in the Ruby language
  • database_cleaner performs DB cleanup in testing
  • capybara simulating a browser, automating a browser or setting expectations using the matchers.

Using Cucumber to test rails 3 application:

1. Create a new Rails application store

$rails new store -d mysql

2. Edit the Gemfile

Include the Cucumber gems in a Rails 3 application

   group :test, :development do
        gem 'rspec-rails'
        gem 'cucumber-rails'
        gem 'capybara'
        gem 'database_cleaner'
 end
3. bundle install

4. Install the cucumber skeleton files to a Rails 3 application.

$ rails generate cucumber:install 

The cucumber-rails generator creates the directories:

features/step_definitions

features/support

The cucumber-rails generator creates the files:

config/cucumber.yml

features/support/env.rb

lib/tasks/cucumber.rake

script/cucumber

5. rake db:create
6. rake db:migrate

7. Run the Cucumber features

$rake cucumber

Create cucumber features:
  • Create a Cucumber Feature for RoR 3 application testing

$vi features/manage_store.feature

  • Cucumber Feature is the business user testing specification written in plain English with a specific format

Feature Format

 Feature: ...
   In order ...
     Some Actor ...
     Should ...

    Scenarior: ...
       Given ...
       And ...

     When ...
     AND ...

     Then ...
     AND ...

Implement the testing steps and Ruby on Rails model code for Cucumber on Rails :

  • Create Cucumber step definitions

$vi features/step_definitions/order_steps.rb

  • Cucumber uses regular expression to match string and pass it to the step definitions
  • Run Cucumber
$rake cucumber
An example might be the ability to manage companies:
Feature: Manage companies

 In order to keep track of companies user should be able to manage companies

Scenario: Create a new company

 Given I am logged in

 When I create a new company named Acme

 Then I should see that a company named Acme exists 

features/

companies.feature

steps/

company_steps.rb

Given == Setup

Given "I am logged in" do

user = Factory(:user)

visits new_session_path

fills_in ‘Login’,

:with => user.login

fills_in ‘Password’, :with => user.password

clicks_button ‘Login’

end

Given "I am logged in" do

user = Factory(:user)

visits new_session_path

fills_in 'Login',

:with => user.login

fills_in 'Password', :with => user.password

clicks_button 'Login'

end

When == Change

When "I create a new company named $name" do |name|

visits new_company_path

fills_in 'Name', :with => name

clicks_button 'Create'

end

Then == Outcome

Then "I should see that a company named $name exists" do |name|

response.body.should =~ Regexp.new(name)

end

At every step you need to run cucumber and check for the result.



Source:RailsCarma 

Integrating Spree In Rails 3.1 Application


Spree is a complete open source e-commerce solution built with Ruby on Rails. It was originally developed by Sean Schofield and is now maintained by a dedicated core team. You can find out more by visiting the Spree e-commerce project page.

It actually consists of several different gems, each of which are maintained in a single repository and documented in a single set of online documentation.

By requiring the Spree gem you automatically require all of the necessary gem dependencies which are:

  • spree_api
  • spree_cmd
  • spree_core
  • spree_dash
  • spree_promo
  • spree_sample

All of the gems are designed to work together to provide a fully functional e-commerce platform. It is also possible, however, to use only the pieces you are interested in. So for example, you could use just the barebones spree_core gem and perhaps combine it with your own custom promotion scheme instead of using spree_promo.

rails_on_rubyInstallation:- It depends on ImageMagick to handle the image processing it does, so we’ll need to install it before we can install Spree. If its not installed already,install it using apt-get(for ubuntu). Once imagemagick is installed,we will create a new rails 3.1 application with the following coSpree In Rails 3.1mmand from terminal. e.g – rails new gps -d mysql (-d mysql specifies that we are going to use mysql as our database)

To install it and all its dependencies, we need to add it in our gemfile. My gemfile looks like this:- source ‘http://rubygems.org’

gem ‘rails’, ‘3.1.3’

Bundle edge Rails instead:

gem ‘rails’, :git => ‘git://github.com/rails/rails.git’

gem ‘capistrano’ gem ‘mysql2′ gem ‘therubyracer’ gem ‘paperclip’, “~> 2.3″ gem ‘tinymce-rails’

Gems used only for assets and not required

in production environments by default.

group :assets do gem ‘sass-rails’, ‘~> 3.1.5′ gem ‘coffee-rails’, ‘~> 3.1.1′ gem ‘uglifier’, ‘>= 1.0.3′ end

gem ‘jquery-rails’

Source : Railscarma

File Uploading using Paperclip Rails Plugin


This is one of the most useful plugin that can be used in your application when you require to upload a file as attachment to your application, its quite easy to use and with the help of paperclip scaffolding you can achieve file upload feature very easily.

Below I have explained the steps to create a simple application using scaffolding that enables the file upload feature with the help of paperclip plugin.

Steps:

Install the required gems to run the paperclip plugin from the below mentioned command,

$ gem sources -a http://gemcutter.org
http://gemcutter.org added to sources

$ sudo gem install view_mapper
Successfully installed view_mapper-0.2.0

1 gem installed Installing ri documentation for view_mapper-0.2.0...
Installing RDoc documentation for view_mapper-0.2.0...

1. First you need to create a rails app and change the database.yml setting and set things to install the plug in $rails student -d mysql

2 Then you have to just install the paperclip plugin into your application from the below mentioned command,

$ ./script/plugin install git://github.com/thoughtbot/paperclip.git

3. Once the plugin is installed, let me show you to create a simple scaffold with paperclip file attachment feature in it.

Just create a simple scaffold and check it out,

$ ./script/generate scaffold_for_view Student name:string branch:string comment:string --view paperclip:photo

Then you need to enter $ rake db:create and $ rake db:migrate

This will create the paperclip file attachment feature, just run $ script/server and check it out. The display looks just like the image i have mentioned at the beginning.

Source: Railscarma.com

Capistrano Deployment with Subversion


Capistrano Deployment

Capistrano is a tool used for automation of the application deployment process. Capistrano is mainly used for deploying rails apps. Changes made to the rails app can be easily transferred to the server using cap deploying.

Capistrano can be configured with any version control system like SVN / GIT for deploying an app. Also, we can define application server type (mongrel, mod_rails / Fcgi) on which the app has be deployed in Capistrano.

Here I’m going to discuss cap deploying an app using SVN with Mongrel cluster as the application server.

Installation:

Capistrano can be installed as a ruby gem as shown below:

$ gem install capistrano


Configuring a rails app to use capistrano:

This can be done by executing the following command from the rails app:

$ capify .

The above command will create a Capfile and config/deploy.rb file.

user@hostname [~/railsapp]$ capify .
[add] writing ‘./Capfile’
[add] writing ‘./config/deploy.rb’

user@hostname [~/railsapp]$ cat Capfile

load ‘deploy’ if respond_to?(:namespace) # cap2 differentiator
Dir[‘vendor/plugins/*/recipes/*.rb’].each { |plugin| load(plugin) }

load ‘config/deploy’ # remove this line to skip loading any of the default tasks

user@hostname [~/railsapp]$ cat config/deploy.rb

set :application, “set your application name here”
set :repository, “set your repository location here”

# If you aren’t deploying to /u/apps/#{application} on the target
# servers (which is the default), you can specify the actual location
# via the :deploy_to variable:
# set :deploy_to, “/var/www/#{application}”

# If you aren’t using Subversion to manage your source code, specify
# your SCM below:
# set :scm, :subversion

role :app, “your app-server here”
role :web, “your web-server here”
role :db, “your db-server here”, :primary => true


PS: As an alternative, we can directly create Capfile and deploy.rb file under the rails app and load necessary data to it using ‘vi’ editor.

Read More: Capistrano Deployment with Subversion

How to Integrate Paypal into Rails Application?


Paypal is an e-commerce based web application, which transfers the amount between two accounts. Almost all US-based companies use Paypal for receiving and doing their payments.

Lets see how to integrate this service in rails application in different steps.

Note: I have tried these steps in development mode, on my local machine. It works fine but haven’t tested in production.

Step 1

a> In case if one doesn’t have a paypal account, go to http://developer.paypal.com and sign up to make an account. Then login using that account.

b> In order to test the application user should have test accounts on paypal.

For example, I made two accounts, one as buyer and another as seller. Both have there secure login and later they can use these accounts to send or receive payments.

c> These pre-configured accounts can be created by going to test accounts tab. Then click on pre-configured option to create test accounts on paypal with little extra information. Please make note of the account id and password generated for both buyer and seller.

d> Now based on requirement check the checkbox of the particular account and click on the link box to enter that particular test account. Clicking on that will redirect you to http://sandbox.paypal.com. Using your account information you one can login to that particular account. These accounts and payments are simulated as any original account will behave.

e> Now lets code our rails application to use these accounts. I am using “Add to cart” option to select few items and add them into cart, by clicking on checkout button, it redirects to paypal site.On next page:-

f> In my cart.rb,paypal_url method to redirect to paypal site:
def paypal_url(return_url,notify_url) #1st url to return to ur own app, 2nd url for paypal to send notification values = { :business => ‘dhyanb_1326716016_biz@gmail.com’, #account generated by paypal :cmd => ‘cart’, :upload => 1, :return => return_url, :invoice => id, :notify_url => notify_url } line_items.each_with_index do |item, index| values.merge!({ “amount#{index+1}” => item.product.price, “item_name_#{index+1}” => item.product.title, “item_number_#{index+1}” => item.product.id, “quantity_#{index+1}” => item.quantity }) end “https://www.sandbox.paypal.com/cgi-bin/webscr?” + values.to_query end

g> In my show.html.erb,i have placed the checkout button with url to return to:
<?php
= button_to “Checkout”, @cart.paypal_url(products_url,payment_notifications_url)
?>

h> You need to be loged in while simulating this service.

i> After clicking on checkout, this will redirect to paypal site with secure connection. This will look like this:-It contains cart details and form for buyer to log in..

j> On this payment page, one needs to give his buyer account id and password to log in. After logging in it will display other user details too with pay-now option. After paying, the buyer can return to his own store by clicking on the link provided on the page.

Notifications from paypal

a>Notifications sent from paypal can be saved in the database.For that we need to have model with proper fields. i.e- rails g model PaymentNotification params:text status:string transaction_id:string cart_id:integer

My notifications controller(create method) will look like this

def create PaymentNotification.create!(:params => params, :cart_id => params[:invoice], :status => params[:payment_status], :transaction_id => params[:txn_id]) render :nothing => true
end

b>There is no direct of testing this,unless deployed in production but it can be tested in the console using curl command. eg-curl -d “txn_id=9JU83038HS278211W&invoice=1&payment_status=Completed” http://localhost:3000/payment_notifications

c>If this command runs without giving any exceptions,then all is well and values will be stored in the database.

Can start making payment now.

Thanks for reading !!!

Source: Railscarma.com