vendredi 15 avril 2016

Shorter code, prevent duplicated call

Right now I have code that looks like this:

def work_with_access_token_or_request_one
    if is_valid_access_token?(params[:code])
        request_client_with_access_token(params[:code])
    else
        request_access_token!
    end
end

In this method I first check if the code I get in the params is valid. If not I request one.

My problem is that right now the method get_access_token is called twice. Once when I check if the access_token is valid and the other time when I request the client.

def get_access_token(code)
    return Okto.request_access_token_from_code(code)
end

I have to do this because the output of get_access_token(code) returns when successful {access_code: 89283} or if an error occurred {error: "not valid"}

def is_valid_access_token?(code)
    result = get_access_token(code)
    return result[:access_code]
end

def request_client_with_access_token(code)
    result = get_access_token(code)
    client = Okto.get_client_from_access_code(result[:acess_code])
end

How can I rewrite my code in work_with_access_token_or_request_one so that only once the method get_access_token is called? Thanks

Aucun commentaire:

Enregistrer un commentaire