Reputation: 1596
I have a controller action somewhat similar to this:
def reports
puts params
@stats = Client.stats(params)
puts params
end
The initial params might look like this:
{ end: '2012-01-01 21:00:19' }
And in my Client model, I have this:
def self.stats(opts)
opts[:start] = (Time.now - 30.days).to_i
...do some calculations..
return stats
end
If I inspect the params object that was sent before and after the function runs, I can see it's been modified by the self.stats method.
In the example above, I'm not sending 'start' in the initial params, the method adds it for the calculations - as expected.
What I was not expecting was that the function would modify the original hash!
Can someone explain why this is happening?
--EDIT--
I forgot to say I tried to create a copy of the params and use that instead, same issue.
def reports
a = params
@stats = Client.stats(a)
puts params
end
The params are still updated?!
Upvotes: 1
Views: 149
Reputation: 3310
That's, because your function call gets a reference to the params not a copy. If you do something like opts[:start] = (Time.now - 30.days).to_i
you are editing the params object.
a = params
: now both variables point to the same place in the memory. You copied the pointer only.
Google for ruby object copy
or ruby deep copy
or search at stackoverflow for it. At a first try you could try params.clone
.
Upvotes: 4
Reputation: 356
Whenever you are updating any value of params, take a copy of params like this
a = params.clone
It will create a new element in memory
if you do like this it wont create a new element in memory it will point the same memory
a = params
Try this
Upvotes: 1