This repository has been archived by the owner on Feb 14, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
应用场景:Rails应用
Aidi Stan edited this page Dec 1, 2018
·
2 revisions
本场景中,我们的目的是在 Rails 模型类内混入 API。
# config/initializers/teambition.rb
require 'teambition/rails/has_teambition_account'
Teambition.client_key = 'YOUR_CLIENT_KEY'
Teambition.client_secret = 'YOUR_CLIENT_SECRET'
Teambition.callback_url = 'YOUR_CALLBACK_URL'
# db/migrate/**************_add_teambition_attributes_to_users
class AddTeambitionAttributesToUser < ActiveRecord::Migration
def change
change_table :users do |t|
t.string :teambition_token
t.string :teambition_id
end
end
end
teambition_id 字段可选(用以方便用户间交互)
通过宏风格函数 has_teambition_account
混入 API,可选参数:
- :token : 模型存储 token 的字段,与上面迁移脚本中的字段相同
- :namesapce : 混入 API 的子命名空间
- 默认值为
:tb
- 设为
nil
时,直接混入模型的命名空间
- 默认值为
# app/models/user.rb
class User < ActiveRecord::Base
has_teambition_account token: :teambition_token
end
# app/controllers/site_controller.rb
class SiteController < ApplicationController
def oauth2_teambition
if current_user.teambition_token && current_user.tb.valid_token?
flash[:success] = '已经绑定!'
redirect_to root_path
else
redirect_to Teambition.authorize_url
end
end
def oauth2_teambition_callback
current_user.teambition_token = Teambition.get_access_token(params[:code])
current_user.teambition_id = current_user.tb.get('api/users/me')['_id']
if @user.save
flash[:success] = '绑定成功!'
else
flash[:danger] = '绑定失败!'
end
redirect_to root_path
end
end
略
注意:回调地址要与 Teambition 应用平台上预留的一致。