我一直在我最新的Rails应用程序中使用Twitter gem,到目前为止没有任何问题。我已注册该应用,已在config/initializers/twitter.rb
中设置了API令牌,并测试了它是否适用于需要gem的自定义rake测试。然而,问题在于,当我尝试从控制器发送推文时,没有任何反应。我的初始化程序如下:
require 'twitter'
Twitter.configure do |config|
config.consumer_key = '###'
config.consumer_secret = '###'
config.oauth_token = '###'
config.oauth_token_secret = '###'
end
显然,我的应用中正确填写了###
。在我的rake文件中,我需要文件顶部的gem,然后能够发送带有Twitter.update(tweet)
的测试推文,但是,我的控制器无法使用相同的语法。
我在这里做错了什么?我是否需要从控制器重新初始化gem?
答案 0 :(得分:2)
经过一些修补,这是一个简单的解决方案:
@twitter = Twitter::Client.new
@twitter.update(tweet)
将它添加到我的控制器方法工作得很好,因为Twitter客户端已经在应用程序启动时进行了身份验证。顺便说一句,这是发送推文的应用程序,而不是通过应用程序发送推文的用户,所以我不需要重新进行身份验证。
答案 1 :(得分:1)
我也在使用Twitter gem,我使用和授权控制器用于我的誓言,直接消息控制器用于Twitter DM,以及前面的ajax。 AppConfig只是一个yml文件,里面有我的信用。
authorizations_controller.rb
class AuthorizationsController < ApplicationController
def new
set_oauth
render :update do |page|
page.redirect_to @oauth.request_token.authorize_url
end
end
def show
@oauth ||= Twitter::OAuth.new(AppConfig['consumer']['token'], AppConfig['consumer']['secret'])
@oauth.authorize_from_request(session['rtoken'], session['rsecret'], params[:oauth_verifier])
session['rtoken'] = nil
session['rsecret'] = nil
session['atoken'] = @oauth.access_token.token
session['asecret'] = @oauth.access_token.secret
redirect_path = session['admin'] ? admin_tweets_path : root_path
redirect_to redirect_path
end
end
direct_messages_controller.rb
class DirectMessagesController < ApplicationController
before_filter :authorize
def create
@client.update("@#{AppConfig['user']} #{params[:tweet][:text]}")
render :update do |page|
page.replace_html 'tweet_update', "Your tweet has been sent to #{AppConfig['user']} and should be updated momentarily."
end
end
end
view.html.haml
#tweet_update
- form_remote_tag :url => direct_messages_url, :method => :post, :loading => "$('tweet_update').hide();$('loading').show()", :complete => "$('tweet_update').show();$('loading').hide()" do
%div{:class => "subheader float_left"}Tweet to Whoever
- if session_set?
%input{:type => "image", :src=>"/images/sendButton.jpg", :class =>"float_right", :style=>"margin-bottom: 4px"}
- else
%div{:class => "float_right", :id => "twitter_login_button"}= link_to_remote image_tag('twitter-darker.png'), :url => new_authorization_url, :method => :get
.float_clear
#tweetbox_bg
- textarea_options = {:id => "tweetbox", :style => "overflow: auto", :rows => "", :cols => ""}
- textarea_value = nil
- unless session_set?
- textarea_options.merge!(:disabled => "disabled")
- textarea_value = "Please login to tweet Whoever!"
= text_area_tag 'tweet[text]', textarea_value, textarea_options
我之前的过滤器'authorize'只是检查会话:
def authorize
session_set? ? set_client : redirect_to(new_authorization_url)
end
希望这有帮助。