Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton in scope of a request in rails [closed]

Using singleton mixin from rails I could create a singleton class in the scope of rails app. But I was wondering Is there a way to create it in the scope of a particular request ?

like image 984
r0h1t4sh Avatar asked Jul 24 '14 07:07

r0h1t4sh


1 Answers

Since a request is tied to a thread, you can use Thread local store:

class RequestSingleton
  def self.instance
    Thread.current['request-singleton'] ||= RequestSingleton.new
  end

  def self.clear
    Thread.current['request-singleton'] = nil
  end
end

Usage:

def index
  RequestSingleton.instance.do_some_setup

  # ...

  RequestSingleton.clear
end

...and anywhere else simply use RequestSingleton.instance to access it.

Since it is thread local, there are no synchronization issues.

like image 93
Uri Agassi Avatar answered Sep 20 '22 11:09

Uri Agassi