Showing posts with label Ruby on Rails. Show all posts
Showing posts with label Ruby on Rails. Show all posts

Wednesday, 28 August 2013

github_api gem with Rails 4: How to import github user information to your Rails Application

This time i am back with one more API feature to the list , that we can incorporate with the existing Rails 4 Application. github api gem is the Ruby wrapper for the GitHub REST API v3.It supports almost all the API methods provided by Github.

Refs
  https://github.com/peter-murach/github
  https://github.com/rest-client/rest-client

Gemfile

Add gem 'github-api' & gem 'rest-client' to your Gemfile. 'rest-client' gem is a simple HTTP and REST client for Ruby. It will help you to get the response data from github after attaching the access token.

Github Controller


As you all know the basic API authentication and after that returning the user back to the callback method, here also there no much changes in the basic functions .First it will authenticate the user to the github app , after that it will redirect the user back to the callback method that we have specified in the redirect url with an authorization code as params , by using the authorization code returned from the github , we will be able to generate a github client object and we can call the get_token method by passing the authorization code as an argument . It will return the Access token to you . by using the access token you can easily call the Git API link by attaching the access token. It will give you the whole user Repository list as JSON. 

Route File


View file



Linkedin Gem with Rails 4 : How to Import Linkedin user information to your Rails Application

All your Linkedin Information's are now just a mouse click away. by using linkedin gem with Rails we can easily import all your linkedin information's  like your skills , contact details , experience details, education details , project details , connection details etc. Now almost all popular websites mainly working in the Professional Networking platform are providing this feature , http://careers.stackoverflow.com/  is my favorite among them , which does the job very brilliant. 

Refs

  https://github.com/pengwynn/linkedin
  http://developer.linkedin.com/documents/profile-fields
  https://gist.github.com/sreeharikmarar/6364970

Gemfile

  gem 'linkedin', '0.4.2', :git => "git://github.com/pengwynn/linkedin.git"

Linkedin Controller


As you all know the basic authentication and the Callback methods , here also first it will  authenticate the user with the linkedin app . You can specify the user access information here in the Linkedin Configuration .What all user fields that your application want to get access. After Authenticating the user it will redirect the user back to the callback method with oauth_verifier as parmas. you will be able to create Access token and access token secret by using the linkedin client object that we have created using the response parameter.

Once the linkedin Client object creation is done , you will be able to access all the user information's like contact details , skills , education details , experience details etc , All the profile field information's are available at http://developer.linkedin.com/documents/profile-fields


LinkedIn is very particular about access to profile fields and you cannot combine multiple fields which requires 2 different type of access. so when you try to get just position details by c.profile(:fields => %w(positions)) it assumes the access of type 'r_basicprofile' whereas educations field require access of type 'r_fullprofile'.so try 2 seperate API calls to retrieve both fields.

"first_name","last_name","headline","positions" available for 'r_basicprofile' member permission,so they can be combined together. but "educations", "three_current_positions", "three_past_positions" , "certifications" etc are available in 'r_fullprofile' . So you have to separate the API calls with respect to the requirements.


Route File

View File 

Friday, 19 July 2013

Integrate Dropbox with your Rails App by using Dropbox API gem with Paperclip

We are going to steal all the Dropbox documents by using Dropbox API with the help of Paperclip. Hey got scared !! .. Oh pls ..  just kidding. But seriously ,We can do that with the help of dropbox-api gem & paperclip .

Step 1

Create an App in Dropbox  Developer  to get the key-Secret pair. You have to set the permission type to "Full Dropbox" mode to get the full Read/Write Access to any file inside the user's Dropbox.

Step 2

Setup your Rails App , include these 2 gems in your Gemfile.

gem 'dropbox-api'
gem "paperclip"

Step 3

Create a file in your config/initializers directory and name it dropbox.rb and put the following line of code inside.


Dropbox::API::Config.app_key    = 'APP KEY'
Dropbox::API::Config.app_secret = 'SECRET KEY'
Dropbox::API::Config.mode       = "dropbox"

Wednesday, 8 May 2013

Linkedin Gem for Rails : How to share dynamic contents to Linkedin from your Rails Application


After Facebook & Twitter share ,its time for Linkedin. I would suggest you to refer my 2 prev posts before going through this article.

Include "linkedin" gem in your Gemfile and bundle .

gem 'linkedin'

Route file:

 match '/linkedin_share/auth'   => 'linkedin_share#auth' , :method => :get , :as => :linkedin_auth

 match '/linkedin_share/callback' => 'linkedin_share#callback' , :method => :get , :as =>  :linkedin_callback


Twitter gem for Rails : How to share dynamic contents to Twitter from your Rails Application

Before going through this post . I would suggest you to go through my previous FB share  post. You will get to know the basic functionality & working from the prev post .After that please go through Twitter gem description.

I hope you have gone through the prev post and you have got some idea about it.

Now we will start with Twitter share implementation.You have to include  "twitter" & "oauth" gems into your Gemfile.

gem 'twitter'

gem 'oauth'

Compared to FB share , here we need to include "Oauth" gem for authenticating the user to twitter and redirect the user back to your applications Callback action.After getting the Oauth Secret Key i.e returning from Twitter you can configure the Twitter gem settings and you can post to twitter from your Rails app.

Tuesday, 7 May 2013

Fb Graph Gem for Rails : How to Post dynamic contents to Facebook Wall from your Rails Application

This post will introduce the usage of fb_graph Gem with your existing Rails Application.fb_graph has already done a lot for you guys to exploit the FB API features with your Rails Application , you can have an eye on this fb_graph Gem before going through this post.

Suppose you have a blogger kind of application, and when you compose a new post , you would like to share the same in your Facebook wall, and also would like to give the same option for all the users ,those who liked your post and would like to share the same in their Facebook Wall.

I think now almost all the websites are using this feature to increase their user traffic , to popularize their sites,  Since Facebook turned out to be a great option for advertising and marketing your site content.

One day i also felt the same and after one complete days of effort ..... i was successful.            I thought i should share the same for you guys to reduce your one days effort ( or may be less ) for implementing this FB share option.

I hope i am not boring you , anyway stop to all kind of rubbish introduction and lets start coding ..

Thursday, 17 January 2013

Ruby On Rails: Omniauth Devise Authentication using Facebook , Google & Twitter.


This post is just a simple straightforward description of Omniauth:Overview , intended for the beginners , those who wants to try the OmniAuth for the first time with Facebook , Google & Twitter. This post will cover all the basic information i.e From creating the app in Facebook, Google & Twitter for getting the secret key To connect these Apps to your Rails Application.

Things in common :

add Devise & omniauth gem to your Gemfile.

gem 'omniauth' 
gem 'devise' 

First of all install Devise into your application.
rails generate devise:install  
You have to create user model using devise ,
rails g devise user  
and after that we need to add 2 more columns i.e "uid" and 'provider' to our user model.

rails g migration AddColumnsToUsers provider:string uid:string
rake db:migrate
 also dont forget to add ":provider" and ":uid" to your attr_accessible also.

 We have done with the things that is common in authentication using facebook,Google, Twitter.

 We will start with Facebook Authentication first 

 Facebook Authentication :

 add gem 'omniauth-facebook' to your gem file.

 First of all you need to create an application in facebook to get the secret key out .


Saturday, 24 March 2012

Ruby on Rails : How to include a page specific JavaScript file in Rails 3.1?

Rails 3.1 application has a new effective way to include a JavaScript file for a particular page without compromising the loading time by using Asset pipeline.


You all know that  in previous versions of Rails, all assets were located in subdirectories of public such as images,javascripts and stylesheets. With the asset pipeline, the preferred location for these assets is now the app/assets directory.Assets can still be placed in the public hierarchy. Any assets under public will be served as static files by the application or web server.

In production, Rails precompiles these files to public/assets by default. The precompiled copies are then served as static assets by the web server. The files in app/assets are never served directly in production.

Monday, 23 January 2012

Ruby on Rails :Cropping images in runtime using Jcrop & ImageMagick

In the previous post i have mentioned about integrating the Jcrop functionality with ImageMagick to hide the selected coordinates  of  the image using a specific color.But here i  am describing on the core feature of Jcrop i.e cropping the image in runtime with the selected coordinates.Here also , we are using ImageMagick in server side to accomplish the whole process.

You all know that Jcrop is a powerful image cropping engine for jQuery. It’s been designed so developers can easily integrate an advanced image cropping functionality directly into any web-based application without sacrificing their time ,flexibility and performance.
ImageMagick is a software suite to create, edit, compose, or convert bitmap images. It can read and write images in a variety of fomats (over 100) like   DPX, EXR, GIF, JPEG, JPEG-2000, PDF, PhotoCD, PNG, Postscript, SVG, and TIFF. We can use ImageMagick to resize, flip, mirror, rotate, distort, shear and transform images, adjust image colors, apply various special effects, or draw text, lines, polygons, ellipses and Bézier curves. ImageMagick have a power full command line tool known as “Convert”. Convert has around 265  options for manipulating images .
So now we are going to integrate this two with Rails ,i wont go in depth of how to create the whole process.
In summery :
  • User choose an image and uploads to a server using paperclip.
  • Wep app shows the images to user and allows him/her to select the desired piece of selection of the image to hide using Jcrop.
  • Using an Ajax post request ,we are sending the parameters (X-cord,Y-cord,Height,Width) to the sever which responsible to crop the portion of the image.
  • The appropriate action in the controller will accept the parameters,and then crop the parameters by using a piece of Image-magic code.

Thursday, 12 January 2012

Ruby on Rails : Image hiding using Jcrop & ImageMagick


You all know that Jcrop is a powerful image cropping engine for jQuery. It’s been designed so developers can easily integrate an advanced image cropping functionality directly into any web-based application without sacrificing their time ,flexibility and performance.
ImageMagick is a software suite to create, edit, compose, or convert bitmap images. It can read and write images in a variety of fomats (over 100) like   DPX, EXR, GIF, JPEG, JPEG-2000, PDF, PhotoCD, PNG, Postscript, SVG, and TIFF. We can use ImageMagick to resize, flip, mirror, rotate, distort, shear and transform images, adjust image colors, apply various special effects, or draw text, lines, polygons, ellipses and Bézier curves. ImageMagick have a power full command line tool known as “Convert”. Convert has around 265  options for manipulating images .
So now we are going to integrate this two with Rails ,i wont go in depth of how to create the whole process.
In summery :
  • User choose an image and uploads to a server using paperclip.
  • Wep app shows the images to user and allows him/her to select the desired piece of selection of the image to hide using Jcrop.
  • Using an Ajax post request ,we are sending the parameters (X-cord,Y-cord,Height,Width) to the sever which responsible to hide the portion of the image.
  • The appropriate action in the controller will accept the parameters,and then hide the parameters by using a piece of Image-magic code.

Tuesday, 3 January 2012

Ruby on Rails : Hosting your Ruby on Rails application in Heroku


In my previous post,i have mentioned about creating a Ruby on Rails application using devise,Now in this tutorial we are going to host Ruby on Rails database backed application (Rails community web site) to Heroku.
you all know that Heroku is a polyglot cloud application platform. With Heroku, you don’t need to think about servers at all. You can write apps in the programming language of your choice, back it with add-on resources such as SQL and NoSQL databases.You can manage your app using the Heroku command-line tool and you deploy code using the Git revision control system, all running on the powerful Heroku infrastructure.
We have created our Rails community website application with a MySQL database support.The only problem that you have to face while hosting your application in Heroku is that Heroku doesn’t support MySQL , Heroku only supports PostgreSQL database for your application.
Sign up : 
Before all, you have to create an account in Heroku,
Install the Heroku Toolbelt on your system :
If you are using a Ubuntu/Linux machine,follow the steps below.
$ apt-add-repository 'deb http://toolbelt.herokuapp.com/ubuntu ./'

$ curl http://toolbelt.herokuapp.com/apt/release.key | apt-key add -

$ apt-get update

$ apt-get install heroku-toolbelt

Ruby on Rails : Creating a simple Ruby on Rails application using Devise.


If you have heard about rails and not yet experienced the power or features that , only rails can give !  this tutorial will help you to create  Simple Ruby on Rails application without worrying too much about the syntax or working of Ruby on Rails.
Here in this tutorial we will create a database backed simple Rails community website application, so that all members can register and sign-in to the website.
About Rails :
Rails is a web development frame work written in ruby language,which has a general MVC ( Model, View, Controller ) architecture.Using a Rails framework will make everything effortless for the developers,who wants to build a powerful/fast application with a less set of code and rails will also help them to achieve more than any other framework can provide.
About Devise :
Simply Devise is a flexible authentication solution for Rails based on Warden. It:
  • Is Rack based.
  • Is a complete MVC solution based on Rails engines.
  • Allows you to have multiple roles (or models/scopes) signed in at the same time.
  • Is based on a modularity concept: use just what you really need.
Lets start coding:
We are going to create a simple rails community website with the help of devise,Before wr entering to our application you should have to gone through the basics of devise.please refer the following link if you want to learn more about devise and rails.
Installation :
I am using ubuntu 11.04, if you are using ubuntu you can follow the below link to install rails in your system.You can also install rails in windows or mac as well.
Creating your application :
Once you have installed every dependencies,you can start creating your first application in rails.
Use “rails new” command to create your application in rails,here we are going to create an application named rails-club.rails
$ rails new rails-club

$ cd rails-club
once you run the above command in your system, you can see that rails has generated so many files and folders inside your rails-club directory.
Editing the Gemfile :
We are going to create this application by using a devise, i have already told you that this is a database backed application.If you are using mysql as your database system then you have to edit your ‘Gemfile’ inside your rails-club directory and add the following line to your ‘Gemfile’.
$ gem 'mysql2', '0.3.6'
Once you have edited the Gemfile,please go through the files and directories the rails has generated,there is file called “database.yml “ in your “config” directory.Change theadapter to mysql2,and then specify your database,username and password . My “database.yml” file contains the following data.
Filepath : config/database.yml
development:
adapter: mysql2
encoding: utf8
reconnect: false
database: mydb
pool: 5
username: root
password: asdfgh

production:
adapter: mysql2
encoding: utf8
reconnect: false
database: mydb
pool: 5
username: root
password: asdfgh
socket: /var/run/mysqld/mysqld.sock

test:
adapter: mysql2
encoding: utf8
reconnect: false
database: mydb_testing
pool: 5
username: root
password: asdfgh
socket: /var/run/mysqld/mysqld.sock
Once you have done all the changes then run the “bundle install” command. This command tells “bundler”, a library used by Rails, to fetch and install all the libraries it needs.
$ bundle install
Installing Devise :
You can use the latest Rails 3 gem with the latest Devise gem, to install the Devise run the following command.
$ gem install devise
After you have installed Devise, you should have to specify the Devise gem to your Gemfile.
$ gem 'devise'
After that you need to run the generator by using the command below.
$ rails generate devise:install
The generator will install an initializer which describes ALL Devise’s configuration options and you MUST take a look at it. When you are done, you are ready to add Devise to any of your models using the generator.
Creating Models :
Here in this application we mainly needs 2 models,one is member model and the other one is contact model,the Member model should contain the member name, email, password, password confirmation etc.So now we are going to create our member model using devise.
$ rails generate devise member
This will create a model member and configure it with default Devise modules.And will also create some more files in your directory. The migration file will located in db/migrate/devise_create_members.rb.After that you should have to run db:migrate as the generator will have created a migration file.
$ rake db:migrate

== DeviseCreateMembers: migrating ==================================
-- create_table(:members)
-> 0.2575s
-- add_index(:members, :email, {:unique=>true})
-> 0.3146s
-- add_index(:members, :reset_password_token, {:unique=>true})
-> 0.4259s
== DeviseCreateMembers: migrated (0.9986s) =========================
Once you run the db:migrate command,rails will create a table called members with the following field that the Devise specified in the migration file.Check the tables has created successfully.
Now we have successfully generated our model.Just run the server by typing “rails server”.
$ rails server

=> Booting WEBrick
=> Rails 3.1.3 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
[2012-01-01 16:40:49] INFO WEBrick 1.3.1
[2012-01-01 16:40:49] INFO ruby 1.9.2 (2011-07-09) [i686-linux]
[2012-01-01 16:40:49] INFO WEBrick::HTTPServer#start: pid=5268 port=3000
copy and past the address http://0.0.0.0:3000/ to your browser search bar,you can see the rails home page .then you also try the following one. The Devise’s magic is comes here.
Here you could see that devise has generated the sign-up and sign-in forms for you.
Here the sign-up form contains only 3 fields email,password & password confirmation,No we have to add the username to the sign-up form.
run the following command to add the username field to members migration.
$ rails generate migration add_username_to_members username:string
This command will generate another migration file in your “db/migrate” directory.
And then again you have to run the “db:migrate” command.Then only the field will add to the members table.
$ rake db:migrate

== AddUsernameTomembers: migrating =================================
-- add_column(:members, :username, :string)
-> 0.3149s
== AddUsernameTomembers: migrated (0.3151s) ========================
Now you check the members table,username field will be added to it.
Creating Views :
Once you have done this you have to generate the Devise views,then only we can edit the sign-up form and add the username field to the form.
$ rails generate devise:views
Once you run this command the devise will generate the whole view files for the members.check “app/views/devise” ,you could see the whole form structure for sign-in,sign-up,forgot password etc.
Then edit the form for sign-up and add the username field to it.Go to“app/views/devise/registration/new.html.erb” and then edit the form like given below.
<h2>Sign up</h2>

<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>

<%= devise_error_messages! %>

<div><%= f.label :username %><br />
<%= f.text_field :username %></div>

<div><%= f.label :email %><br />
<%= f.email_field :email %></div>

<div><%= f.label :password %><br />
<%= f.password_field :password %></div>

<div><%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation %></div>

<div><%= f.submit "Sign up" %></div>
<% end %>

<%= render :partial => "devise/shared/links" %>

Now check the sign-up form again you can see the username field in it.
Lets create our second model Contact.Here we doesn’t use devise generator ,in contact model we need only 2 fields, phone number, address.
$ rails generate model contact
Edit the migration file of contact and specify the 2 fields as shown below.
class CreateContacts < ActiveRecord::Migration
    def up
        create_table :contacts do |t|
       
        t.string :mobile , :null => false, :default => “”
        t.string :address , :null => false, :default => “”

    end

end

    def down
        drop_table :contacts

    end
end
After that run db:migrate command to create a table contacts in our database.
$ rake db:migrate

== CreateContacts: migrating =======================================

-- create_table(:contacts)
-> 0.2141s
== CreateContacts: migrated (0.2142s) ==============================
Creating Controller :
We haven’t created an home page yet,so now we are going to create a controller for that.
$ rails generate controller home
And then create a new index file for home controller like “app/views/home/index.html.erb” and then add the following .
<% if member_signed_in? %>

<h3>you have succesfully signed in</h3>
<%= link_to "Sign Out", destroy_member_session_path, :method => :delete %>

<% else %>

<h1> welcom to rails community</h1>
<%= link_to "Sign In", new_member_session_path, :method => :get %>
<%= link_to "Sign up", new_member_registration_path, :method => :get %>

<% end %>
Once you have done ,you have to remove the index page in public folder,and then you should have to reset the root path to “home#index” page.
app/config/routes.rb
add the line
root :to =>'home#index'
Now we have to override the devise controller ,then only we can call the objects from 2 models (contact,members),so now we are going to create a new controller called “registration”.
$ rails generate controller registration
Open the controller file in “app/controllers/registration_controller.rb”,and then edit the file as shown below.
Filepath : app/controllers/registration_controller.rb
class RegistrationController < Devise::RegistrationsController

    def new

        @member= Member.new
        @contact = Contact.new

    end

    def create

        @member = Member.new
        @member.username = params[:member][:username]
        @member.email = params[:member][:email]
        @member.password = params[:member][:password]
        @member.password_confirmation =params[:member][:password_confirmation]

        @contact = Contact.new
        @contact.mobile = params[:contact][:mobile]
        @contact.address = params[:contact][:address]
        @member.valid?

        if @member.errors.blank?

            @member.save
            @contact.member = @member
            @contact.save
            redirect_to dashboard_path

        else
            render :action => "new"
        end
    end

end

Once you have done the above step,we are going to create a view for our registration controller, create file called “new.html.erb”,in your “app/views/registration/” directoryand then add the following.
Filepath : app/views/registration/new.html.erb
<h2>Sign up</h2>

<%= form_tag(member_registration_path,:method => 'post') %>
<%= devise_error_messages! %>
<table>

<tr>
<td>Username : </td>
<td><%=text_field_tag "member[username]",@member.username %></td>
</tr>

<tr>
<td>Email : </td>
<td><%=email_field_tag "member[email]",@member.email %></td>
</tr>

<tr>
<td>Password : </td>
<td><%=password_field_tag "member[password]",@member.password %></td>
</tr>

<tr>
<td>Retype password : </td>
<td><%=password_field_tag "member[password_confirmation]",@member.password_confirmation %></td>
</tr>

<tr>
<td>Mobile : </td>
<td><%=text_field_tag "contact[mobile]" ,@contact.mobile %></td>
</tr>

<tr>
<td>Address : </td>
<td><%=text_area_tag "contact[address]" ,@contact.address ,:rows => 10, :cols => 25 %></td>
</tr>

<tr>
<td><%= submit_tag nil, :class => "form_submit"%></td>
</tr>
</table>
<br />
<%= render :partial => "devise/shared/links" %>
We have to mention the relationships between 2 models (member ,contact ).here the relationship will be as follows.
Filepath : app/models/member.rb
class Member < ActiveRecord::Base

devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable

attr_accessible :email, :password, :password_confirmation, :remember_me, :username
has_one :contact
end
Filepath : app/models/contact.rb
class Contact < ActiveRecord::Base
    
   belongs_to :member
end
Now refer the registration controller file in app/controllers/registration,here after completing the registration & the values that the member entered is stored in the table successfully ,i just redirected the member to the dashboard page.So we have to add that page to our home controller.
Filepath : app/views/home/dashboard.html.erb
<p>hi welcome to Ruby community. you have successfully registered to your rails club account</p>
<%= link_to "Sign out", destroy_member_session_path, :method => :delete %>
You have to specify this path in our routes.rb file
Filepath : app/config/routes.rb
devise_for :members,:controllers => { :registrations =>'registration'}
match 'dashboard' => 'home#dashboard'
Conclusion :
Finally  the application has almost done,so run the server and try our application in your machine whether everything working perfectly or not.This is just a skeleton of our application,we can add a lot more css to design our application to make everything looks perfect.
I hope that this tutorial will help you to start experiencing on Ruby on Rails application.If you facing any problems when you start trying out this application on your working environment,feel free to shoot your questions or suggestions. If you wants to get the fullcode of this application,please refer.
I have also uploaded this application in Heroku.Check out the following link.