0

I am using Octokit so as to login.

helper_method :user

def show
end 

def user
  client = Octokit::Client.new(access_token: session[:access_token])
  begin
    @user = client.user
  rescue => e
    redirect_to root_path
    return
  end
end 

The root_path is in the config

  root to: 'home#new'

The rescue es executed, however the redirect_to isn't working, it return to the same view as the main method. Note: I read in many post that putting return fix it, nevertheless it didn't

nacho c
  • 311
  • 1
  • 3
  • 15
  • Remove the ':' from root_path and make sure root_path is defined in your config/routes.rb file. Also, 'return false' to halt further execution. – bkunzi01 Dec 05 '16 at 19:14
  • @bkunzi01 I misspelled. I updated the post. The root is defined and the root_path is defined properly – nacho c Dec 05 '16 at 19:21

1 Answers1

1

Your code is calling the redirect_to method, but the rescue block is subsequently returning nil. Instead, combine the redirect and return into a single statement:

client = Octokit::Client.new(access_token: session[:access_token])
begin
  @user = client.user
rescue => e
  redirect_to root_path and return
end

In fact you don't need the return at all, unless there is something after this statement in the method. This is because in Ruby the last statement is implicitly returned.

Ryenski
  • 9,582
  • 3
  • 43
  • 47
  • I tried and it didn't work. The problem is that the code is into a helper method and not in the method controller? – nacho c Dec 05 '16 at 20:09
  • I updated the post in order to clarify that @mysmallidea – nacho c Dec 05 '16 at 20:11
  • Does Octokit really raise an exception if there is no user? – Ryenski Dec 05 '16 at 20:22
  • yes, it does. I figured out the problem. I was calling the method in a helper_method, so the method is called from the view and not from the controller – nacho c Dec 05 '16 at 20:24
  • 1
    That would do it :) Maybe it makes more sense to set @user in a `before_action` - that way it would be available to the view and the controller, and you wouldn't have to keep calling on Octokit::Client. – Ryenski Dec 05 '16 at 20:26