LoginSignup
1
1

More than 5 years have passed since last update.

Using Omnicontacts to get mail contacts from Google

Last updated at Posted at 2014-09-11

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 into Gemfile 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 file omnicontacts.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 the main_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 to http://localhost:3000.

You can refer example at link: http://omnicontactsvinhnguyen.herokuapp.com/ or https://github.com/vinhnguyenleasnet/omnicontactvinhnguyen

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1