2

Ruby でサンプル コードを実行して、Blogger 3.0 用の Google の API を使用してブログ投稿リストを取得しようとしています。これはコードです:

require 'rubygems'
require 'google/api_client'
require 'sinatra'
require 'google/api_client'
require 'logger'

enable :sessions

def logger; settings.logger end

def api_client; settings.api_client; end

def blogger_api; settings.blogger; end

def user_credentials
  # Build a per-request oauth credential based on token stored in session
  # which allows us to use a shared API client.
  @authorization ||= (
    auth = api_client.authorization.dup
    auth.redirect_uri = to('/oauth2callback')
    auth.update_token!(session)
    auth
  )
end

configure do
  log_file = File.open('blogger.log', 'a+')
  log_file.sync = true
  logger = Logger.new(log_file)
  logger.level = Logger::DEBUG

  client = Google::APIClient.new
  client.authorization.client_id = 'XXXXXXXXXXXXX'
  client.authorization.client_secret = 'XXXXXXXXXXXXX'
  client.authorization.scope = 'https://www.googleapis.com/auth/blogger'

  blogger = client.discovered_api('blogger', 'v3')

  set :logger, logger
  set :api_client, client
  set :blogger, blogger
end

before do
  # Ensure user has authorized the app
  unless user_credentials.access_token || request.path_info =~ /^\/oauth2/
    redirect to('/oauth2authorize')
  end
end

after do
  # Serialize the access/refresh token to the session
  session[:access_token] = user_credentials.access_token
  session[:refresh_token] = user_credentials.refresh_token
  session[:expires_in] = user_credentials.expires_in
  session[:issued_at] = user_credentials.issued_at
end

get '/oauth2authorize' do
  # Request authorization
  redirect user_credentials.authorization_uri.to_s, 303
end

get '/oauth2callback' do
  # Exchange token
  user_credentials.code = params[:code] if params[:code]
  user_credentials.fetch_access_token!
  redirect to('/')
end

get '/' do
  # Fetch list of posts
  result = api_client.execute(:api_method => settings.blogger.posts.list, :parameters => {'blogId' => 'XXXXXXXXXXXXX'})
  [result.status, {'Content-Type' => 'application/json'}, result.data.to_json]
end

実行中のローカル アプリケーションに接続すると (認証後)、次の「sinatra」エラーが表示されます。

#<NameError: undefined local variable or method `blogger' for #<Sinatra::Application:0x92ac2dc>>

それは私には少しあいまいです。何か案が?

4

0 に答える 0