Skip to content

Instantly share code, notes, and snippets.

@charlespeach
Created May 31, 2017 03:03
Show Gist options
  • Save charlespeach/86a3dbc455a6ba282ae87b31ca04e443 to your computer and use it in GitHub Desktop.
Save charlespeach/86a3dbc455a6ba282ae87b31ca04e443 to your computer and use it in GitHub Desktop.
Global variable using ruby singleton pattern
class SQSToken
class << self
def get_token
puts @@sqs_token ||= magic_method_which_gets_the_token_the_first_time
end
# Replace this method with a call to what ever magic
# code that gets a new token only if required
def magic_method_which_gets_the_token_the_first_time
puts 'ive run!'
"magic string!"
end
end
end
SQSToken.get_token # 1st run it will set the token and set a class variable
SQSToken.get_token # 2nd run it will return the previously set variable
# ruby sqs.rb
# ive run!
# magic string!
# magic string!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment