Skip to content

Instantly share code, notes, and snippets.

@asaaki
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asaaki/0cbe8e8b3176fb78f755 to your computer and use it in GitHub Desktop.
Save asaaki/0cbe8e8b3176fb78f755 to your computer and use it in GitHub Desktop.
[Ruby] retry a block until a condition is met
module Token
module_function
MAX_RETRIES = 3
TokenTakenError = Class.new(StandardError)
def token_generator
# SecureRandom.hex(32)
("a".."z").to_a.sample
end
def token_exists?(token_candidate)
# ApiToken.where(token: token_candidate).exists?
("a".."m").to_a.include?(token_candidate)
end
# More DB-like behaviour (unique index constraint)
def raising_token_exists?(token_candidate)
fail TokenTakenError, "Token already taken!" if token_exists?(token_candidate)
end
# retry times loop
def generate_token_with_times
MAX_RETRIES.times do
token_candidate = token_generator
return !token_exists?(token_candidate) && token_candidate
end
end
# begin while loop
def generate_token_with_while
begin
token_candidate = token_generator
end while token_exists?(token_candidate)
token_candidate
end
# loop loop
def generate_token_with_loop
token = loop do
token_candidate = token_generator
break token_candidate unless token_exists?(token_candidate)
end
end
# retry loop
def generate_token_with_rescue_retry
token_generator.tap do |token_candidate|
raising_token_exists?(token_candidate)
end
rescue TokenTakenError
retry if _retries = (_retries || 0) + 1 and _retries < MAX_RETRIES
fail "Too many retries!"
end
# endless retry loop
def generate_token_with_rescue_endless_retry
token_generator.tap do |token_candidate|
raising_token_exists?(token_candidate)
end
rescue TokenTakenError
retry
end
end
# calls
Token.generate_token_with_times
Token.generate_token_with_while
Token.generate_token_with_loop
Token.generate_token_with_rescue_retry
Token.generate_token_with_rescue_endless_retry
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment