codedecoder

breaking into the unknown…


1 Comment

installing REST API tool in firefox

I have created a sample REST API in this post. To access any API service, You need to write REST client code in your application. But you can try out any API services in your browser itself, by installing one of the many available tools. Good REST client tools is available for both Firefox and Chrome. I will explain, installing one of the tool and how to use it in Firefox.

STEP 1 : Installing the REST client tool

=> open your Firefox browser

=>You can find the REST client tool, through below steps

click tool tab at top of browser  -> click web developer  from the list -> click get more tools ->click Extensions down the adds on tab -> search rest client -> install the one with the title : RESTClient, a debugger for RESTful web services by click the button add to Firefox

=> Once installed, you can see a brown square icon with a circle in it at top right hand side of the browser. click it to start the tool

STEP 2: Understanding the tool

The REST client UI in browser look like this

Firefox rest client

Firefox rest client

You can test any REST API with the above tool. To use any API, you need to have information about its various services, see the sample API created in this post and read its documentation. These are the things, you need to fill up in the above UI, before making a call.

Authorization :

It list various type of authorization you need to setup before accessing any API. In the sample API I have provided basic authorization with username and password. Thus, click on basic authorization, fill the username and password and click O.K. It is one time process and will set your authorization for the current session

Content Type :

You need to setup, the content type of your request body. In API documentation you can find various type of content type supported by it. You can set content type by : click on header -> click on custom header -> In the popup, fill up Content-Type in name field and application/xml or application/json or application/x-www-form-urlencoded or anyother as per your need  in the value field-> click O.K

This can be also a one time process and you do not need to change it untill, you want to try out with any other content type.

API Requests :

Set, proper method, url and body in the above Rest Client UI as specified by the API documentation and then click the send button

API Response :

Once, the request is completed, you can see Response tab appearing at the bottom with Header, Response Body(raw), Response Body(highlight),  Response Body(Preview). The Header will contain the status of the response i,e success or failed and the response body will contain the data returned by the API to you


23 Comments

Sample REST API in Rails

I have tried to define and explain API in this post.  I again, put it in simple words “API is program which let the user to use methods of your application from outside the application“. I will create a REST API here which will implement CRUD ( create, read, update, delete ) operation on users table from outside the application. I assume you all have implemented CRUD for user in your application. The API implementation will remain same, with below difference.

=> In normal case, you have form new.html.erb and edit.html.erb, which provide UI to user to register themselves and edit there profile respectively. But for API you do not need any view as a user do not interact with Your application directly, instead you specify that data, the third party should send to you.

=> There will be no new and edit action in controller, as we do not need any view here

=> In normal application we do user authentication with devise etc, We need to skip that and introduce http authentication

=> We do not do any redirect in our controller action, but just return some data with status code and success or failure message. We may return data in json or xml or any other formate say SOAP. As per convention, you should return data as requested by client calling your API services, so for json request return json data and for xml return xml data

=> API do not have any user interface like navigation link or form to fill up by user etc. So for API you need to document the things, so that third party can use it easily. I will write the documentation for the API we create here in STEP 4

STEP 1: writing the routes

namespace :api do
 resources :users, :defaults => { :format => 'xml' }
end

I have put the routes, within api namespace, in this way, it will not conflict with users controller of your actual application, if you have one. If you do not have any, you can simply use  resources :users, :defaults => { :format => ‘xml’ } , but I suggest to always use a namespace and group all the controller related to your API in api folder only. Also, I have set the default :formate here as xml . If you do not set it, rails will consider it as a html request if user forget to pass any formate

STEP 2: generating the model


class User < ActiveRecord::Base
  attr_accessible :first_name, :last_name, :email, :password, :password_confirmation, 
                  :temp_password

  validates :email, :first_name, :last_name, :presence =>true
  validates_uniqueness_of :email

end

Thus in model we have validated email and other things, the user calling our API must provide these things. Thus while creating a user the caller must pass email, :first_name and :last_name. we will  generate password  dynamically and let him change it later on

STEP 3 : generating the users controller

class Api::UsersController < ApplicationController
  http_basic_authenticate_with :name => "myfinance", :password => "credit123"

  skip_before_filter :authenticate_user! # we do not need devise authentication here
  before_filter :fetch_user, :except => [:index, :create]

 def fetch_user
    @user = User.find_by_id(params[:id])
  end

  def index
    @users = User.all
    respond_to do |format|
      format.json { render json: @users }
      format.xml { render xml: @users }
    end
  end

  def show
    respond_to do |format|
      format.json { render json: @user }
      format.xml { render xml: @user }
    end
  end

  def create
    @user = User.new(params[:user])
    @user.temp_password = Devise.friendly_token
    respond_to do |format|
      if @user.save
        format.json { render json: @user, status: :created }
        format.xml { render xml: @user, status: :created }
      else
        format.json { render json: @user.errors, status: :unprocessable_entity }
        format.xml { render xml: @user.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    respond_to do |format|
      if @user.update_attributes(params[:user])
        format.json { head :no_content, status: :ok }
        format.xml { head :no_content, status: :ok }
      else
        format.json { render json: @user.errors, status: :unprocessable_entity }
        format.xml { render xml: @user.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    respond_to do |format|
      if @user.destroy
        format.json { head :no_content, status: :ok }
        format.xml { head :no_content, status: :ok }
      else
        format.json { render json: @user.errors, status: :unprocessable_entity }
        format.xml { render xml: @user.errors, status: :unprocessable_entity }
      end
    end
  end
end

STEP 4 : creating API Documentation

Your API is ready with step 3, but how other people will use it. You need to tell them, how to use it. Let us Document the things

API USAGE DOCUMENT
___________________________________________________________________
Basic Authentication:
    username: myfinance
    password: credit123

Content Type :
   application/xml or application/json

Body:
   You can pass xml or json data in Body
   
   sample json body

    {
     "email" : "test@yopmail.com", 
     "first_name" : "arun", 
     "last_name" : "yadav"
    }

   Sample xml body

    <user>
      <email>"test@yopmail.com"</email>
      <first-name>arun</first-name>
      <last-name>yadav</last-name>
    </user>

NOTE : Content Type should be set to application/xml for xml data in body 
and to application/json for json data in body

API Requests:

=> listing users
   url: http://localhost:3000/api/users
   method: GET
   body : not needed

=> Retrieving User detail
  url: http://localhost:3000/api/users/:id 
  method: GET
  body : not needed

=> creating users
   url: http://localhost:3000/api/users
   method: Post
   Body : It can be xml or json

=> Updating User
  url: http://localhost:3000/api/users/:id 
  method: PUT
  Body : It can be xml or json
  
=> Deleting User 
  url: http://localhost:3000/api/users/:id 
  method: DELETE
  body : not needed

STEP 5: testing the API

You need to write a REST client to use any API. I have explained it in this post. You may also try it out by Installing any REST client in your browser. I have explained installing REST client for Firefox in this post.

You will find method, url, body. header, authentication etc field there, fill the detail from the documentation instep 4. On submitting the detail, you will get back response. Hope it works for you and you get the basic understanding of API creation 🙂


18 Comments

google drive download upload with oauth2 in rails

Now a days many people use to store their document online in their emails, google drive etc. There may be case, when user want to upload some document in proof of, say there loan application or other claims etc from cybercafe, where their local system is not available, so it is good idea to provide this feature in your application if it need user to upload some document. I will explain the implementation here.

STEP 1: Understanding the flow

-> google provide API to access its google drive.

To use google API you need to create a development account with it and get client_id and client_secret . These two will be needed to validate the application trying to connect with the google API. Infact, all API provider whether FB, twitter or any other needs client_id and client_secret  issued by them. More information of google drive API is availabe here .

-> User need to login to there google account to access their google drive

google provides single sign on (SSO) for its API. We will use oauth2 strategy for this. oauth2 gem is available to ease our task.

-> downloading the document of loged in user

We will use google-drive-ruby gem for it. it will manage all upload and download on behalf of the loged in user. The basic implementation is available here . In this post, I will download file from google drive to temp folder of the application. Once, you have the file you can write methods which let the user to download to his system or upload to some other place. But that part I will cover in some other post

STEP 2: Install the required gems

Add below to Gemfile

gem 'google_drive'
gem 'oauth2'

Run bundle install on project root

STEP 3: creating Google API credential

go to https://code.google.com/apis/console and login with your gmail credential. It will ask you to create a project. click the create project button and on the next page which list all the API services, click on drive api button, accept the term and conditions, now you will see that the API button become green and also API access link appear in the side bar. click it, you will see create oauth2 client button, on the next page enter the required detail. See here if you get in problem while creating the credential

I fill below details:

product name : myfinance

Product logo   : select any logo if you have

Home page Url: localhost:3000

Now, click the next button, select web application and click create client id , so Now you have the below detail .

Client ID : 565763748610-uo2pjbbpg544ujcnuu7j28b6bjsl5llf.apps.googleusercontent.com
Email address : 565763748610-uo2pjbbpg544ujcnuu7j28b6bjsl5llf@developer.gserviceaccount.com
Client secret :     UUpzejV2gtYlJe1sFVENYUGN
Redirect URIs :     http://localhost:3000/oauth2callback
JavaScript origins : http://localhost:3000

STEP 4 : creating user authentication with oauth2

oauth2 strategy works with below principal

-> You tell it the SSO url where a user will be authenticated. Here, we are authenticating with google so it will be https://accounts.google.com

-> You need to tell oauth where the authenticated user will be redirected back in your application with the response. In step 2, you have seen that the redirect URI is https://localhost:3000/oauth2callback i,e oauth2 will send back the user to this url, let us write a routes for this url. Add below line to config/routes.rb file

match ‘oauth2callback’ => ‘documents#set_google_drive_token’ # so now we will write our stuff in set_google_drive_token action of documents controller.

Let us first write a library  for user authentication with oauth. Create lib/google_drive folder and create google_docs.rb file in it. It will look like this

module GoogleDrive

  class GoogleDocs

    attr_writer :client_id, :client_secret, :redirect_uri

    def initialize(client_id, client_secret, redirect_uri)
      @client_id = client_id
      @client_secret = client_secret
      @redirect_uri = redirect_uri
    end

    def create_google_client
      OAuth2::Client.new(
        @client_id, @client_secret,
        :site => "https://accounts.google.com",
        :token_url => "/o/oauth2/token",
        :authorize_url => "/o/oauth2/auth")
    end

    def set_google_authorize_url
      client = create_google_client
      client.auth_code.authorize_url(
        :redirect_uri => @redirect_uri,
        :access_type => "offline",
        :scope =>
          "https://docs.google.com/feeds/ " +
          "https://docs.googleusercontent.com/ " +
          "https://spreadsheets.google.com/feeds/")
    end

  end
end

The create_google_client method instantiate oauth2 class and set_google_authorize_url send the user to gmail for login

STEP 5 : Writing the controller code

create documents_controller.rb file. It will look like this

  
require 'google_drive/google_docs'
class DocumentsController < ApplicationController
 before_filter :google_drive_login, :only => [:list_google_docs]

 GOOGLE_CLIENT_ID = "565763748610-uo2pjbbpg544ujcnuu7j28b6bjsl5llf.apps.googleusercontent.com"
 GOOGLE_CLIENT_SECRET = "UUpzejV2gtYlJe1sFVENYUGN"
 GOOGLE_CLIENT_REDIRECT_URI = "http://localhost:3000/oauth2callback"
  # you better put constant like above in environments file, I have put it just for simplicity
  def list_google_docs
    google_session = GoogleDrive.login_with_oauth(session[:google_token])
    @google_docs = []
    for file in google_session.files
      @google_docs  < < file.title     
    end   
   end

  def download_google_docs
    file_name = params[:doc_upload]
    file_path = Rails.root.join('tmp',"doc_#{file_name}")
    google_session = GoogleDrive.login_with_oauth(session[:google_token])
    file = google_session.file_by_title(file_name)
    file.download_to_file(file_path)
    redirect_to list_google_doc_path
  end

  def set_google_drive_token
    google_doc = GoogleDrive::GoogleDocs.new(GOOGLE_CLIENT_ID,GOOGLE_CLIENT_SECRET,
                GOOGLE_CLIENT_REDIRECT_URI)
    oauth_client = google_doc.create_google_client
    auth_token = oauth_client.auth_code.get_token(params[:code], 
                 :redirect_uri => GOOGLE_CLIENT_REDIRECT_URI)
    session[:google_token] = auth_token.token if auth_token
    redirect_to list_google_doc_path
  end

  def google_drive_login
    unless session[:google_token].present?
      google_drive = GoogleDrive::GoogleDocs.new(GOOGLE_CLIENT_ID,GOOGLE_CLIENT_SECRET,
                     GOOGLE_CLIENT_REDIRECT_URI)
      auth_url = google_drive.set_google_authorize_url
      redirect_to auth_url
    end
  end
end

We are authorizing the user in the before filter google_drive_login. after authentication it take user to the redirect action set_google_drive_token, here we can retrieve the authentication token from the params[:code] send back with oauth returned url. I have stored that token in session[:google_token], so that I do not need to authenticate the user again. In download_google_docs method we need the name of the file we want to download fron google drive and the path of file where we need to download it.

STEP 6: writing routes for the controller action

Add below routes to config/routes.rb

match 'oauth2callback' => 'documents#set_google_drive_token' # user return to this after login
match 'list_google_doc'  => 'documents#list_google_docs', :as => :list_google_doc #for listing the 
                                                                                  #google docs
match 'download_google_doc'  => 'documents#download_google_docs', :as => :download_google_doc #download

STEP 7: Generating the views

So ,in view list_google_docs.html.erb will list all the docs with a radio buttons(we are downloading one at a time for now) within a form,the form will submit to the download_google_docs action, which after downlaod will be redirected back to the listing page.

<div>Select The document You want to Download</div>
<%= form_tag download_google_doc_path do %>
<% @google_docs.each do |doc|%>
<div><%=radio_button_tag “doc_upload”, doc %> &nbsp;<%=doc%></div>
<%end%>
<%= submit_tag  “Download” %>
<%end%>

That’s all, You can see that, the selected file get downloaded to temp folder

 

Reference :

https://developers.google.com/drive/credentials


Leave a comment

steps to move from git to svn

I have been working with Git for long, but recently client asked to move the repository to SVN. I do not know, what benefits it will give over Git . Personally, I prefer working with git and find it better in managing my source code. A comparative analysis of commands used in both is available here . The one clear distinction between git and svn is that, in Git your code history is maintained both locally and remotely i,e say you are working on master branch locally, so when you do git diff it will compare changes from your local master branch rather than the remote master branch,  but with svn all history are maintained at some detached remote branch, and when you do diff , it compare the changes from that remote branch. Anyway, I follow the below steps.

STEP 1: Install svn in your system

$ sudo apt-get install svn

STEP 2: check that svn working properly

$ svn -h # It will list all the commands you can use with svn, You can use it whenever you want to know about a svn command

   add
   blame (praise, annotate, ann)
   cat
   changelist (cl)
   checkout (co)
   cleanup
   commit (ci)
   copy (cp)

You can apply on any of these command to know more about them

$ svn ci -h # so it will tell about ci command
commit (ci): Send changes from your working copy to the repository.
Valid options:
  -q [–quiet]             : print nothing, or only summary information
  -N [–non-recursive]     : obsolete; try –depth=files or –depth=immediates
  -m [–message] ARG       : specify log message ARG
  -F [–file] ARG          : read log message from file ARG
  –force-log              : force validity of log message source

STEP 3: hosting ths SVN repository

This part is need to done by the client. There are a number of  service provider there like Assembla, Unfuddle , BeanStalk, CVSDude, ProjectLocker ,  etc. Go to any of them, create a account and get the url of the empty svn repository to which the developer will push there code . say you are provided  with below url by the client

http://subversion.my-finance.com/repos/my-finance/

STEP 4:  cloning the svn repository

$ cd Projects # I keep all my projects in this folder

$ svn checkout http://subversion.my-finance.com/repos/my-finance/    arun-finance # so the code will copy to arun-finance folder, if not given name it will be copied with the repository name i,e my-finance

$ cd arun-finance # it contain only a .svn folder as no code is added to it yet

STEP  5:  Adding Files to SVN

I copied all the file from my local git repository except .git and .gitignore folder to this folder(now git is not needed)

$ svn status
?       db
?       Gemfile_back
?       spec
?       public
?       test
?       product.xml
?       app

The ? marks in svn means the file are untracked i,e not yet added to svn

$ svn add .
svn: warning: ‘.’ is already under version control # as the empty repository I cloned already have a .svn folder, so I added them as below

$ svn add script config lib Gemfile README.textile features public test product.xml app log Rakefile  Gemfile_back spec config.ru coverage vendor Gemfile.lock db

$ svn status
A       README.textile
A       public
A       public/favicon.ico
A       public/document_viewer
A       public/document_viewer/document_viewer.js
A       public/system
.

.

A       log/development.log
A       log/thin.log

So all files are now added to svn, but I have added lof file also, I do not want that so reverted as below

$ svn rm log –force # I have added log to svn, but not want it so reverted back

STEP 6 :  Pushing the code to the remote repository

$ svn ci -m”repository moved from git to svn”
Authentication realm: <http://subversion.my-finance.com:80&gt; Subversion Repository
Password for ‘arun’: # give your system password
Authentication realm: <http://subversion.my-finance.com:80&gt; Subversion Repository #
Username: arun123
Password for ‘arun123’: # the password with which you access the remote repository
Adding         Gemfile
Adding         Gemfile.lock
Adding         Gemfile_back
.

.

Transmitting file data ……………………………………………………………………………………………………………………..Committed revision 1.

So,  Your code is now available at the remote repository. You can see it your self by going to the repository url in the browser

$ svn up # this will update any change in the remote branch to your local branch
At revision  1.

STEP 7 : Deploying  remote svn repository to server

You can write deployment script for it, but for time being I did it manually. The logic is simple, You just need to login to your server and replace the source code taken from git earlier to the code pulled from the new svn repository.

$ ssh root@10.1.5.189 # my server ssh path
root@10.1.5.189’s password: year206
[root@cms05 ~]# cd ~/loan_projects

[root@cms05 loan_projects]# ls # showing the folder hosted with git

my_finance

[root@cms05 loan_projects]# cp -R my_finance my_finance_git # backup the folder as my_finance_git, to revert back if anything goes wrong

[root@cms05 loan_projects]# rm -rf my_finance # You need to clone ths svn with the name of folder you are removing as your nginx or the other server is configured to read the source code from this folder, if name get changed you need to make change there also, to make it work again

[root@cms05 loan_projects]# svn checkout http://subversion.my-finance.com/repos/my-finance/   my_finance

[root@cms05 loan_projects]# cd my_finance

[root@cms05 my_finance]# svn up # It will update the recent code from remote. run it evertime you want to deploy the recent code

[root@cms05 my_finance] #   move to the my_finance folder and run all the command you run earlier before restarting your server

[root@cms05 my_finance]# sudo /etc/init.d/nginx restart # restart the server

Now, Go to your site in browser, It is up as usual


6 Comments

rails with bootstrap

Bootstrap is one of the most talked about project of twitter on github . It is a total html5 and css3 compliant solution for your UI . Basically, It is a kind of reverse engineering for a UI developer. Let me put up it in simple words. When a UI designer, design a site, he write css and keep adding on them as need arises . So he first write classes for managing overall layout, then for navigation, button forms etc. Bootstrap do it all for you in a single file bootstrap.css. But, here you need to be aware of the different class of css, you can use in particular condition, say different css for layout or Navigation etc. They are quite simple to figure it out from bootstrap online documentation. Bootstrap also provides a no of  plugin written with jquery to work seamlessly, with its css and without much work.

Let me first list the url where you can find different bootstrap resources :

=> List of all opensource projects of twitter hosted on github

http://twitter.github.com/

=> Download Page

You can download bootstrap from below link. It have download bootstrap and download bootstrap source. You will just need bootstrap css and js file for your application, but I suggest you to download it with the source as it will also contain examples and demo along with the required js and css files. If you downlaod with source the js and css file will be available in /doc/assets/js and /doc/assets/css folder respectively.

http://getbootstrap.com/getting-started/

The, bootstrap downloaded from here, will contain everything offered by bootstrap, But say you need only tooltip and popover plugin and do not want a huge bootstrap.min.js or bootstrap.js (both file are same, but first one is minified so, it is of smaller size) to be render. In such case you can customize the js and css file before downloading at below link,

http://getbootstrap.com/customize/

Here, you can also see the css variables, which show you the default settings like @bodyBackground, @linkcolor etc. Well, the bodycolour by default set to white. You want to set it to orange. Strange, you can’t customize these variables here. Don’t worry we will do it later on by writing custom css to override bootstrap default css. personally, I never customize bootstrap from above link, but download the original source and later on do customization in code whenever needed.

NOTE :  If you have downloaded the bootstrap with source, in docs/assets/js folder you will find js files of individual components, like tooltip, popover etc. The individual css component are present in less folder of downloaded source. So, If you are more concerned about load time of your page, keep adding the required component as need arises, instead of including bootstrap.min.js or bootstrap.min.css file itself. But the component js file or the css files in less folder  is not minified, better minified it before including as it will reduce the file size considerably. online tools is available there for minification of js and css files.

=> classes used in creating Layouts

Layout can be classified into two categories : fixed and fluid. The fixed layout is static and measure width, height etc in terms of pixle, while fluid layout measure in terms of percent. Fluid layout adept itself to different screen size. I always prefer fluid layout. Sample code for layout design is available here.

http://getbootstrap.com/getting-started/#examples

You can see that, You can create a layout with few classes. Those classes are as below

Fixed Layout classes -> container, row, span2 span6 etc, offset2 offset4 etc

Fluid Layout classes -> container-fluid, row-fluid, span2 span6 etc, offset2 offset4 etc

=> classes used in creating different component

Now, your layout is ready and you want to create other components like navbar, footer, sidebar etc. But, what class I should use. Well the sample code of every component and its classes is available at the below link

http://getbootstrap.com/components/

=> Basic classes, images and icons

Now, you want to beautify the content of your site. You can find detail of classes related to links, text, list, images etc at the below link

http://getbootstrap.com/components/#glyphicons

NOTE :  Bookmark, these links or just http://getbootstrap.com/components , above are just different tabs of this site.

So, now I assume that, You have your bootstrap’s css and js file to design your whole site and You know about different classes you may need to build it or atleast you know the place from where you can figure out the things which fullfill your need. Great…we will now apply these things to our rails project. Lets call it bootstrap_demo.

$ rails new bootstrap_demo

$ cd bootstrap_demo/

$ rails generate controller bootstrap_demos index

$ rails s

load index page in browser at http://localhost:3000/bootstrap_demos . You will get routes not found error. well add the routes as below in /config/routes.rb file

resources :bootstrap_demos

Reload the Page…. Well You get simple page with message BootstrapDemos#index. Fine, Let us now decide on layout of our site. So this is the spec.

-> Navigation at the top and Footer at bottom

-> Body have two column. Left column for side bar navigation and right column for main content

-> Main content layout will varies for each page.

Top two requirement is consistent through out the site. Let us Put this layout in application.html.erb file. This html file will look like this.

application.html.erb

Now reload the page http://localhost:3000/bootstrap_demos

No css reflected, page look colorless and without any style. It is expected as we have not yet added bootstrap css to our application. copy the bootstrap.min.js or bootstrap.css file from your downloaded folder(present in bootstrap/css folder if downloaded compiled version and in doc/assets/css if downloaded with source code) to the app/assets/javascript and app/assets/stylesheet folder of your application. Now rails3 will automatically load this file. If you are working in some other framework or if bootstrap file is not loaded, you need to link it explicitly in the <head> tag as you may be doing it for other files  as below

<link href=”css/bootstrap.min.css” rel=”stylesheet”>  assuming the path is css/bootstrap.min.css relative to the html file

Let us assume that the bootstrap.min.js file is linked properly in head. So refresh the page again….and here you can see all the css reflected with the page looking as below.

index1

So, you can see that, we have our layout structured through application.html.erb file with top navigation bar, two column for content, and three column footer. Here, you should note that, use and nesting of container-fluid, row-fluid, span4 span12 etc and offset class. You can nest them within one other to make as many block as you wish.

container-fluid  -> It will define the container or box for you. You can create a single container for whole application or multiple box. I have use three container-fluid, one for top nav, one for body content and one for footer

row-fluid  -> It will define no of racks or row in your box, each roe occupy the whole space of the container, within which it is placed.

span4 -> It define, blocks within a row. span4 means, the div with this class will occupy 4 part of the row, a row-fluid consist of 12 part.

span8 -> it means the div with this class will occupy 8/12 of whole width of row-fluid

offset1 -> offset define gap between two blocks, see it use in footer

NOTE:

-> In any row the sum of number used against span and offset should not increase 12
-> The well class, I have used in application.html.erb has nothing to do with layout, it just make a DIV to rise with light background colour. I have used it to make the blocks we have created get visible to you as we do not have any real content there. Use, it if you want your div to rise
So, our layout is ready, Let us add custom content to our index page of bootstrap_demo controller. index.html.erb will look like this

content
Refresh the page and Now it will look like this, with two new column created for the main content one for article and the other for image

index file with content

Wao…we have achieved so much without writing single line of css. What about bootstrap jquery plugin. Let us try tool-tip plugin form bootstrap. This will show some tip about the link when user hover over it

NOTE : bootstrap plugin is build over jquery, So You must include jquery.js also when including bootstrap.js.

copy the jquery.js and bootstrap.js from the downloaded bootstrap to your app/assets/javascript folder. Now modify, your index.html.erb as below. bootstrap documentation on its implementation is available here

index file with js code

Now refresh the Page. It will look like this, and when you hover over a link it will show the tip about that link

bootstrap tool-tip demo

APPLYING THEMES :

The bootstrap we have downloaded comes with default themes i,e background colour, link colour etc. We can customize them as per our need. But what if, something suits our need without customization or we need to customize on smaller extent. Well bootswatch provides a no of themes for bootstrap. List of all the themes is available here . Download the themes you liked and just replace the bootstrap.css file in your application with the bootstrap.css available in the downloaded theme. say , I downloaded, bootstrap.min.css for amelia and replaced the existing bootstrap.min.css in my app/assets/stylesheet folder with it. Refresh the page….wao now the site looking much colourful.

amelie theme

CUSTOMIZING BOOTSTRAP CSS

coming soon……

for time being refer it at below link to get some idea

http://stackoverflow.com/questions/10451317/twitter-bootstrap-customization-best-practices

References:
http://bootstrapthemes.quora.com/25-Awseome-Twitter-Bootstrap-Themes-For-Better-Bootstrap-Designs   # contain free demo templates

http://www.sitepoint.com/beyond-bootstrap-foundation-frameworks-never-heard/ # alternative framework to bootstrap


1 Comment

sending exception notifcation in rails

You have deployed, your application in production. It is running smoothly. But you want to keep track of bugs and errors, so that you can fix them as soon as possible. A no of gems is available here on toolbox. Errbit and Airbrake are high on popularity and provide better tracking of bugs and error. But they are paid services. If you are willing to pay, you can go with it. Since, My goal was to get informed of any exception in production as soon as it appear, so that I can fix it as soon as possible, an email notification with trace of error is sufficient for me. This is very easy to achieve with exception_notification gem. It is easy to install and work with. Just follow the below simple steps.

STEP 1: Add the gem to your gem file

gem ‘exception_notification’

STEP 2: install the bundle

$ bundle install

STEP  3: Add below configuration to your target environment i,e staging, production etc

MyFinance::Application.configure do
  ....other configuration....

  # configuration for exception notifier

  config.middleware.use ExceptionNotifier,
  :email_prefix => "MyFinance",
  :sender_address => %{"myfinance" <myfinance@trantorinc.com>},
  :exception_recipients => %w{arun.singh@yahoo.com kapil@gmail.com},
  :email_headers        => { "X-Custom-Header" => "Myfinance exceptions" },
  :smtp_settings => {
    address: "smtp.gmail.com",
    port: 587,
    domain: "example.com",
    authentication: "plain",
    enable_starttls_auto: true,
    user_name: "arunprojects@gmail.com",
    password: "happyarun"
  }

end

The configuration options are self explanatory. Add, all the person who need to be notified of exceptions in :exception_recipients list as shown above. The top 3 options (:email_prefix ,  :sender_address,  :exception_recipients) are compulsory . You can ignore :email_headers. You can also ignore the :smtp_settings, if you want the notifier to use the smtp_setting defined for other mail of your application. In my case, I do not want that, as I was using third party paid service  to deliver mails to user. So, I have passed the :smtp_settings to the exception notifier.

The two recipient will now get notification about any exception in you application. If you want to see it working before deploying to staging or production environment, just add the above configuration in step 3 to development.rb file, restart server, create some error on any page, load the page which throw the error. check the recipient email, you will see the exception notification email there.


7 Comments

Bundler::GitError with passenger

Recently, I get into a strange problem. I’am using jqgrid_for_rails gem for jqgrid implementation. There are some changes in the gem which is available in the master branch of github but not in the gem published or rubygems.org, I think they have still not released the new changes to rubygems.org. So, I linked the source code of the gem to its git repository in my Gemfile as below

gem 'jqgrid_for_rails' # it will fetch the gem from rubygems.org. I replaced it with the below line

gem 'jqgrid_for_rails', :git => 'http://github.com/Juanmcuello/jqgrid_for_rails.git' # it will 
fetch the gem from its git repository

I run bundle install , which installed the gem and everything worked fine in development. I pushed the code to production. restart nginx and passenger, but my application breakdown with below error notified by passenger,

http://github.com/Juanmcuello/jqgrid_for_rails.git(at master) is not checked out. Please run bundle install(Bundler::GitError)

Bundler::GemError

SO, the error is obvious, and they are also suggesting the solution. Well, I have already run bundle install any way I run it again

$ bundle install

.

Using jqgrid_for_rails (1.0.1) from http://github.com/Juanmcuello/jqgrid_for_rails.git (at master) # it means the gem is allready there

$ bundle show jqgrid_for_rails
/home/arun/Projects/third-pillar/vendor/bundle/ruby/1.9.1/bundler/gems/jqgrid_for_rails-62969c07e4ca # so the gem is installed

But still the error persists. No doubt, Passenger is not able to read the installed gem from rvm when installed with source as git repository, this may be because, when you install a gem from rubygems.org it get installed in gems folder of your gemset but if you specify some other source as we have done for jgrid_for_rails above the gem will get installed into bundler folder of your gemset. Somehow passenger do not able to read it from there. I tried without passing the git source and running bundle install again and things work this time.

But, My purpose is not solved as my application is UP but I can’t use jqgrid_for_rails gems feature which is must for me. So I restored back my gemfile and looking deep for some more solution. I got the solution in bundler site itself here

SOLUTION :  After deployment of your code run bundle install – -deployment instead of bundle install

when you run bundle install, the bundler install the gem into gems folder of your gemset i,e the gem resides in rvm of your system

when You run bundle install – -deployment  the bundler install the gems locally in your project’s vendor/bundle/ruby/1.9.1/gems folder i.e the gems are always available in your project and bundler will tell passenger to look for gems from this folder instead of RVM