0

I created an HTML app which is meant to be run locally using rackup config.ru -p 3000 in "production".

This app communicates with RabbitMQ via the Bunny gem, and publishes messages when I hit various endpoints via Ajax.

I also have two methods called init and deinit which setup and destroy global variables related to the RabbitMQ server: $connection, $channel and $exchange.

These things are not meant to be done every single request though, in fact it crashes RabbitMQ at least 50% of the time.

What I need is to run init when starting the server, and deinit when I CTRL+C out of it, so these global variables are created only a single time and are available for use by the rest of the app (across multiple requests).

I just have no idea how to go about doing this.

Here is how I'm defining my methods.

def init
  $conn = Bunny.new(host: SETTINGS['host'])
  $conn.start
  $ch = $conn.create_channel
  $x  = $ch.default_exchange
end

def deinit
  puts "\nExiting..."
  $ch.close
  $conn.close
end
Tallboy
  • 12,847
  • 13
  • 82
  • 173
  • Why not show a minimal example of your code showing HOW you are defining your globals? Explanations are not nearly as good as a code sample. Using globals isn't a good practice, instead I'd recommend using constants in the main body of your code, and don't define them and destroy them, simply assign to them once and be done with it. Needing to assign and destroy a global makes no sense as they are supposed to exist for the full lifespan of an app. – the Tin Man Apr 02 '15 at 16:23
  • Sure, I can do that. Give me 30 seconds. – Tallboy Apr 02 '15 at 16:25
  • You can also look into Ruby's [`BEGIN {...}` and `END {...}`](http://ruby-doc.org/docs/keywords/1.9/Object.html#method-i-BEGIN) also. – the Tin Man Apr 02 '15 at 16:30
  • I have to use globals even though it's not ideal just because it's using a shared library that is used in many places, and I don't have time to change it everywhere. So where would you recommend I add it then in Sinatra? I'm not sure how BEGIN/END would help (or are used) – Tallboy Apr 02 '15 at 16:52
  • see http://stackoverflow.com/q/2582822/335847 – ian Apr 05 '15 at 22:15
  • If you add that as an answer iain I'll mark it. – Tallboy Apr 06 '15 at 01:07
  • I've voted to close it as a duplicate, as I didn't really work for it :-) If it doesn't attract more votes to close, just add a quick note at the bottom of your question to look so that people don't waste their time with the comments. – ian Apr 10 '15 at 18:32

0 Answers0