2011-07-17 19 views
0

から救出私はステータスの更新に失敗したときに救出しようとしているtweets_controllerTwitterの宝石

#called when user submits twitter form 

def message 
      unless current_user 
      session[:twitter_message] = params[:twitter_message] #sets the message from the form so it's available for send_tweet in tweet.rb after we pass through omniauth 
      redirect_to '/auth/twitter' #redirects to authorize via omniauth/twitter and create the user 
      else 
      @auth = Authorization.find_by_user_id(current_user) 
      Tweet.update_status(@auth, params[:twitter_message]) 
      redirect_to edit_user_path(current_user), :notice => "Tweet sent." 
      end 
end 

を持っています。

def self.update_status(auth, msg) 

    @token = auth.token 
    @secret = auth.secret 
    @message = msg 
    @t = Twitter::Client.new 

    Twitter.configure do |config| 
     config.consumer_key = '[key]' 
     config.consumer_secret = '[secret]' 
     config.oauth_token = @token 
     config.oauth_token_secret = @secret 
     config.gateway = '[gateway_url]' 
    end 

    ret = @t.update(@message) 
    tweet ||= Tweet.create_from_response(ret, auth.id) 

    rescue Twitter::Error => e 
     logger.error "#{e.message}." 
end 

私はコントローラを介して私のユーザーにそれを表示することができますので、私はエラーメッセージが表示されます。どうすればよい:これは私の知る限り得るように見えることができますようです - 私は、ユーザーにフラッシュメッセージを表示したいのですが、 ?

答えて

1

アプリケーションに基づいてカスタム例外を作成してスローすることができます。

次に、あなたのモデルにアプリ/ libに/ could_not_update_status_error.rb

class CouldNotUpdateStatusError < StandardError 
end 

rescue Twitter::Error => e 
    logger.error "#{e.message}." 
    raise CouldNotUpdateStatusError.new("Could not update status") 

そして、あなたのコントローラで

else 
    begin 
    @auth = Authorization.find_by_user_id(current_user) 
    Tweet.update_status(@auth, params[:twitter_message]) 
    redirect_to edit_user_path(current_user), notice: "Tweet sent." 
    rescue CoundNotUpdateStatusError => e 
    # Do error stuff 
end 

別のオプションは、救助リターンを行うことであろうあなたのTwitter :: Error句でfalseを返し、ifステートメントでupdate_status呼び出しをラップします。ただし、例外より堅牢なソリューションです。

+0

ありがとうございました。私はこれを試してみましょう。クラス宣言以外のapp/libファイルには何も必要ありませんか? – Slick23

+0

'CouldNotUpdateStatusError.new("ステータスを更新できませんでした ")との関係で'間違った数の引数(1のために1)が発生しました '' – Slick23

+0

これはTwitterのプロパティです::追加のデータを期待してエラーが発生しました。 ErrorはStandardErrorを拡張します。私は私の答えを更新しました。 – Gazler