Some time ago I missed one of the cool features from the time I worked with JavaEE, that was a request scope for some variables.
I know the instance variables on controllers do a great job simulating it, but I needed to access context in a completely different part of the application, that wasn’t always called from controllers, variables that should be scoped to that request.
So I thought, I could create something like that for my rails app.
To start, I created a file called ‘request_scope.rb’ in the lib folder, with something similar to this (I’ll not post the actual file here because it is from a client’s project)
class RequestScope def self.start_scope raise "request_context already set" if Thread.current[:request_context] Thread.current[:request_context] = {} end def self.end_scope raise "request_context already nil" unless Thread.current[:request_context] Thread.current[:request_context] = nil end def self.scoped_hash raise "request_context not initialized" unless Thread.current[:request_context] Thread.current[:request_context] end def self.[](name) self.scoped_hash[name] end def self.[]=(name,val) self.scoped_hash[name] = val end end
That will allow me to do things like:
RequestScope['alpha'] = 1 RequestScope['alpha']
And for that to work, as a real request scope, I just needed to add one bit of code to the application_controller.rb of my application:
class ApplicationController < ActionController::Base around_action :define_request_scope def define_request_scope EnvConfig.start_scope begin yield ensure EnvConfig.end_scope end end end
There is one trick thou, if you need to read or write to the request context in any other filters, remember that they need to be defined after the “define_context_scope”, because the filters are executed in the order they are defined.
So, what do you think about this approach to create a request scope? would you do different? do you see any problems in this implementation?
Can you explain the problem this solves? What does this allow you to do now?
The problem I was solving with this, was to access in an easy way, information related to the current user request in “commands” implemented under the lib directory and in models, the code didn’t belong in controllers…