LoginSignup
165

More than 5 years have passed since last update.

Google DriveのスプレッドシートにRubyでアクセスする方法

Last updated at Posted at 2014-12-20

いつ使えるの?

Google Drive の spreadsheet に、rubyでアクセスしたい時に使えます。

公式リポジトリ

google_drive

google_drive をインストール

Gemfile
gem 'google_drive'
$ bundle install --path vendor/bundle

で gem をインストールします。

OAuth2.0を利用してアクセス

今回は、リフレッシュトークンを使ってアクセスします。

ここを参考にしながら取得しました。▷ Google API OAuth2.0のアクセストークン&リフレッシュトークン取得手順メモ

Google Developers Consoleにアクセス

Google Developers Console

「Drive API、Drive SDK」の値

APIと認証から、「Drive API」と「Drive SDK」をONにします。

on.png

新しいクライアント IDを作成

clientnew.png

リフレッシュトークンを取得

クライアント ID、クライアント シークレットをメモ。続いて、新しいクライアントを利用して、リフレッシュトークンを取得します。

app.png

https://accounts.google.com/o/oauth2/auth?client_id=[先ほど取得したクライアントID]&redirect_uri=[先ほど設定したリダイレクトURI]&scope=https://www.googleapis.com/auth/drive&response_type=code&approval_prompt=force&access_type=offline

認証ボタンをクリック。

ninsyou.png

認証ボタンをクリックした後、URL欄で認証コードが「〜code=」以下に示されているので、その部分をメモ。

ターミナル上でIDとURIやキー等を用いて以下のようなコマンドを実行する

curl -d client_id=[クライアントID] -d client_secret=[クライアントシークレット] -d redirect_uri=[リダイレクトURI] -d grant_type=authorization_code -d code=[認証コード] https://accounts.google.com/o/oauth2/token

JSONに「リフレッシュトークン」が含まれて返ってきます。

{
  "access_token" : "dfor39.5Asgerib2qoPSSv-A6sfvL53I6PHCZ1cS-LHZFX4qiqjP7hwerwFwrOY6OCe_BgPnZGZZ4-w",
  "token_type" : "Bearer",
  "expires_in" : 3600,
  "refresh_token" : "1/-LZ_AVkmvtBzdmKVKul5vaHBwerwerwreM3s6D8soMEudVrK5jSpoR30zcRFq6"
}

spreadsheetにアクセス

アクセスしたいシートを作成( https://docs.google.com/spreadsheets/d/1dUS554DEogp9J2aWJmt2MEFvzNMlrogYtoGOQdV0/edit

sp.png

これでアクセスに必要な クライアント ID、クライアント シークレット、リフレッシュトークンがそろいました。

app/controllers/home_controller.rb
class HomeController < ApplicationController
require "rubygems"
require "google_drive"

  def show
    client_id     = "987654321797-lijuhygtfr34567.apps.googleusercontent.com"
    client_secret = "poiuytrew-KVyaUT"
    refresh_token = "1/-LZ_AVkmvtBzdmKVKul5vaHBgfdswerD8soMEudVrKr987654321"
    client = OAuth2::Client.new(
        client_id,
        client_secret,
        site: "https://accounts.google.com",
        token_url: "/o/oauth2/token",
        authorize_url: "/o/oauth2/auth")
    auth_token = OAuth2::AccessToken.from_hash(client,{:refresh_token => refresh_token, :expires_at => 3600})
    auth_token = auth_token.refresh!
    session = GoogleDrive.login_with_oauth(auth_token.token)
    ws = session.spreadsheet_by_key("1dUS554DEogp9J2aWJmt2MEFvzNMlrogYtoGOQdV0").worksheets[0]

    # レコード数を取得
    p ws.num_rows
    # カラム数を取得
    p ws.num_cols
  end
end

"1dUS554DEogp9J2aWJmt2MEFvzNMlrogYtoGOQdV0"

の部分はアクセスしたいスプレッドシートのURL https://docs.google.com/spreadsheets/d/1dUS554DEogp9J2aWJmt2MEFvzNMlrogYtoGOQdV0/edit の "1dUS554DEogp9J2aWJmt2MEFvzNMlrogYtoGOQdV0" の部分を使用します。

アクセスすると見事「7」「3」と表示されました。

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
165