I'm new to rails, I'm trying to figure out if rails have a request context where I can store variables and access them across the context of the request? I'm using rails 4.2.11.
I've tried to have a before filter in
class ApplicationController < ActionController::Base
before_action :set_request_context
def set_request_context
Thread.current[:request_context] = {:correlation_id => "some_unique_id"}
end
end
And then I'm accessing this variable else where in code. I'm sure this is not the right way because the application runs on ngnix and it may not guarantee that a request would be served by a single thread throughout.
When a request is processed within the method of the mapped controller a new object of a class is instantiated which needs access to this request_context.
class CreditCardPaymentsController < ApplicationController
def new
@paypage_id=PaypageIdRequest.new(:merchant_id => merchant_id)
end
end
Within the methods of PaypageIdRequest class I need to access the correlation_id I've set in :request_context. Please note that I cannot send the variable to PaypageIdRequest class at the time of initialisation because there are so many places I'll have to send this variable and it would be bad practice to send it at all places considering Aspect Oriented Programming.
Yes, Rails offers this functionality through it's CurrentAttributes API.
https://api.rubyonrails.org/classes/ActiveSupport/CurrentAttributes.html
In Rails (and Rack applications in general) you have env
which is a hash like object that contains the request object. env
is used by middleware like Warden to inject themselves into your application.
However this is not a global. It is available in the routes, the controller and in views but not in models which are not request aware, neither is it available on whatever else you add to the MVC model like service objects or decorators unless you pass it.
If you want it to be available in your PaypageIdRequest
class you need to use constuctor or method injection or make whatever you are saving a global.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With