Today, when I'm working on company, my colleague asked me: "Do you use Omnicontacts gem to get mail contacts from Google?". After 30 minutes research about this gem, now I'll write a post "Using Omnicontacts to get mail contacts from Google".
- First, create new rails app:
mkdir omnicontacts
cd omnicontacts/
rails new .
- After run command
bundle install
, let's add OmniContacts intoGemfile
as a dependency:
gem 'omnicontacts'
bundle install
again.
- You need generate a controller to handle callback returned from Google.
rails g controller main index contact
class MainController < ApplicationController
def index
end
def contact
end
end
- As for Omniauth, let's go to
/config/initializers/
directory and create new fileomnicontacts.rb
require 'omnicontacts'
Rails.application.middleware.use OmniContacts::Builder do
importer :gmail, "client_id", "client_secret, {:redirect_path => "/oauth2callback", :ssl_ca_path => "/etc/ssl/certs/curl-ca-bundle.crt"}
end
To add client_id
and client_secret
, please access Google API Console and Create new Client ID
- After generated
main_controller
, let's update the routes file:
Omnicontacts::Application.routes.draw do
match "/contacts/:importer/callback" => "main#index", :via => [:get]
match "/oauth2callback" => "main#contact", :via => [:get]
# You can have the root of your site routed with "root"
root 'main#index'
end
- The list of contacts will be accesses via the
omnicontacts.contact
key in the environment hash. So, please edit themain_controller
file:
class MainController < ApplicationController
def index
end
def contact
@contacts = request.env['omnicontacts.contacts']
respond_to do |format|
format.html
end
end
end
- After that, we need edit two files in Views folder
/main/index.html.erb
<h2>OmniContacts Example</h2>
<a href="/contacts/gmail">Gmail</a>
/main/contact.html.erb
<% unless @contacts.nil?%>
<% @contacts.each do |c|%>
<ul>
<li><%= c[:name]%> : <%= c[:email]%></li>
</ul>
<%end%>
<%end%>
- Done, now you can run
rails s
and access tohttp://localhost:3000
.