dsp_099
dsp_099

Reputation: 6121

Constant being overridden on request in ruby/sinatra

I don't want to copy the whole code here because it's rather bulky but here's the gist of it:

require 'sinatra'

SOME_DATA = get_hashes_from_db

get '/' do

 # SOME_DATA's hashes are filtered using .delete
 result = process_data SOME_DATA, request

 response.body(JSON.generate(result))
end

Every request, a list of hashes is filtered based on some params sent in the request. Some fields are present in SOME_DATA are used for this filter but they are stripped for when it's time for them to be sent back using .delete to erase the whole key. Example:

Before filtering:

{'condition' => 'rainy', 'data' => 'get an umbrella!'}

After filtering:

{'data' => 'get an umbrella!'}

Now the issue: Even though the original constant that's passed into the function is then diced and reassigned a dozen times, calling the .delete method on the variable that's been reassigned from the original STILL affects the original. On request 1 I'll have, say, 10 hashes with 10 fields each. On request 2 I'll have 10 hashes, but with 2-5 fields each.

I think I'm having the same issue as this guy, however I've tried passing it with .clone hoping it'd resolve the issue but it has not.

I've encountered this particular problem before but I don't think I ever resolved it. Why does it still overwrite the original even though (in the above pseudocode) I pass SOME_DATA.clone to process_data?

Upvotes: 0

Views: 55

Answers (1)

zed_0xff
zed_0xff

Reputation: 33217

try something like this:

SOME_DATA = get_hashes_from_db.freeze

now it will raise an exception when some code tries to modify SOME_DATA

also if get_hashes_from_db returns an Array or Hash then you'd need to freeze each array/hash element as well.

Upvotes: 1

Related Questions