Question

I have some instance methods in a class that must be called in a sequence. The failure of any method in a sequence will require the previous method to be re-called. I'm storing the result of each successful method call in a class variable:

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

I would like to get rid of those conditionals, but don't know how to perform the block only if there are errors present in the returned hash.

Was it helpful?

Solution

This whole method requires a rewrite...but to answer your question, why wouldn't the following work?

my_proc = ->(){ fill_me_with_something }
my_var ||= my_proc.call

raise StandardError if my_var.nil?

Editing my answer to better answer the question...The syntax:

 my_proc  =   ->(a,b){ a + b } 

Is another way to express a block, for all intents and purposes:

 my_proc(1, 5)   #=> 6

You can also express Procs in this format:

 my_proc = Proc.new{ |a, b| a + b }

The advantage of using a Proc is that you can set your block-like behavior to some variable, and then invoke call on that proc whenever you want, which, in your case, is when some other variable is blank.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top