Question

I am currently in the need to access params inside a serializer but not sure what would be the best approach here.

Basically I just to access the timezone which is inside the params hash to respond with the model's time attribute converted to that timezone.

Was it helpful?

Solution

I created a simple struct object to allow access to both the current user and the params hash, like so:

SerializerScope = Struct.new(:current_resource_owner, :params)

I put that declaration in an initializer, and then I use it in my main API controller:

def default_serializer_options
  {
    scope: SerializerScope.new(current_resource_owner, params)
  }
end

Within my serializers, I then have access to scope.current_resource_owner and scope.params.

Testing becomes a little more work as you need to properly stub within tests:

serializer_scope = SerializerScope.new
serializer_scope.current_resource_owner = # a user
serializer_scope.params = {} # override and re-stub within controller action tests
MySerializer.any_instance.stub(scope: serializer_scope)

Obviously, be sure that when you access params from inside a serializer, certain common params like :id could change from controller to controller.

This is all using AMS ~> v0.8.0.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top