Domanda

I'm developing an API controller. Naturally, before the response is sent to the client, I do some data 'grooming'. To this end I have a few specialized private methods. I would like to be able to set an instance variable in the controller called 'resp' (as 'response' seems to be a reserved Rails term) and have those methods modify the response directly instead of passing it back and forth. So I declare

attr_accessor :resp

and set it in one of the endpoints like so

resp = movie.hash_attributes_for_movie_details(current_user)

This causes an error down the line as resp is not being set this way and ends up being nil. If I set the instance variable directly

@resp = movie.hash_attributes_for_movie_details(current_user)

I'm able to 'get' it, but the setter is not setting anything. What am I missing?

Thanks in advance.

È stato utile?

Soluzione

Ruby has a gotcha when using setters on the same object: You have to use the syntax self.setter = value. Otherwise, ruby thinks you are creating a local variable.

So, on your case, you would need to change your code to:

self.resp = movie.hash_attributes_for_movie_details(current_user)

Yes, it is a bit annoying, but it is a tradeoff we have to pay to have the syntax for local variables and for methods to be the same.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top