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

class GithubController < ApplicationController
def authorize
@github = Github.new :client_id => "app_id", :client_secret => "secret_key"
address = @github.authorize_url :redirect_uri => "http://#{request.host_with_port}/github/callback", :scope => 'repo'
redirect_to address
end
def callback
authorization_code = params[:code].to_s
@github = Github.new :client_id => "app_id", :client_secret => "secret_key"
token = @github.get_token(authorization_code)
access_token = token.token
# EX: https://api.github.com/user/repos?access_token=xxxxx
response = RestClient.get("https://api.github.com/user/repos?access_token=#{access_token}")
datas = JSON.parse(response)
puts "datas : #{datas}" # It will print the whole github response details as a json
redirect_to root_path # any path that you want to redirect the user after importing
end
end

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

get '/github/authorize' => 'github#authorize'
get '/github/callback' => 'github#callback'
view raw route.rb hosted with ❤ by GitHub

View file

<%= link_to "Import Github", '/github/authorize'%>
view raw view.html.erb hosted with ❤ by GitHub


No comments:

Post a Comment

Note: only a member of this blog may post a comment.