我在一个类中有一些实例方法,必须按顺序调用。序列中任何方法的失败都需要重新调用之前的方法。我将每个成功的方法调用的结果存储在一个类变量中:
class User
@@auth_hash = {}
def get_auth_token
result = MyApi.get_new_auth_token(self) if @@auth_hash[self]['auth_token'].blank?
if result['Errors']
raise Exception, "You must reauthorize against the external application."
else
@@auth_hash[self]['auth_token'] = result['auth_token']
end
@@auth_hash[self]['auth_token']
end
def get_session_id
result = MyApi.get_new_session_id if @@auth_hash[self]['session_id'].blank?
if result['Errors']
get_auth_token
# Recursion
get_session_id
else
@@auth_hash[self]['session_id'] = result['session_id']
end
@@auth_hash[self]['session_id']
end
end
我想摆脱这些条件,但不知道只有在返回的哈希中存在错误时如何执行该块。